Unconstization

Discussion in 'Mac Programming' started by Miglu, Jun 19, 2011.

  1. macrumors member

    Joined:
    Jan 22, 2010
    #1
    I am using NSData to store structs in an NSMutableArray. However, NSData returns the structs as const, so I can not change them. How to unconst them? Also, does a better way to store structs in an NSMutableArray exist?
     
  2. jiminaus, Jun 19, 2011
    Last edited: Jun 19, 2011

    macrumors 65816

    jiminaus

    Joined:
    Dec 16, 2010
    Location:
    Sydney
    #2
    Store the structs not in NSData but in NSMutableData, then send a mutableBytes message to get a non-const pointer.

    Do you have to use a struct? What about using an actual object instead?

    For example, instead of:
    Code:
    struct InfoAboutThingy {
       int info1;
       int info2;
       /* etc. */
    };
    
    Use instead:
    Code:
    @interface InfoAboutThingy : NSObject {
    @public
      int info1;
      int info2;
      /* etc. */
    }
    @end
    
    @implementation InfoAboutThingy
    @end
    
    Then you can store the info directly in NSArray without having to deal with NSData.


    EDIT: Or wrap the struct in an object if you have to use a struct. For example:
    Code:
    @interface InfoAboutThingyHolder : NSObject {
    @public
        InfoAboutThingy infoAboutThingy;
    }
    @end
    
    @implementation InfoAboutThingyHolder
    @end
    
     
  3. macrumors 68000

    Sydde

    Joined:
    Aug 17, 2009
    #3
    This is the way of Objective-C, and a very good habit to get into. If you need to use a struct, define it as an ivar of an object. Then the object can provide either components of the struct or simply a pointer to it.

    Why do this? Because at some point down the road, you might find it convenient to write this object to a file or stream. By adopting NSCoding protocol, your object's data becomes very portable and your work is greatly simplified.
     
  4. chown33, Jun 19, 2011
    Last edited: Jun 19, 2011

    macrumors 603

    Joined:
    Aug 9, 2009
    #4
    In Objective-C, InfoAboutThingy is only a struct tag, not a type name. If you want it to be a type name, you must use the typedef keyword.

    As a struct tag, this would be needed:
    Code:
    @interface InfoAboutThingyHolder : NSObject {
    @public
        struct InfoAboutThingy infoAboutThingy;
    }
    @end
    

    This differs from C++, where struct tags are automatically usable as type names without a typedef:
    http://www.cplusplus.com/doc/tutorial/structures/
     

Share This Page