Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

Miglu

macrumors member
Original poster
Jan 22, 2010
74
0
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?
 
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
 
Last edited:
Do you have to use a struct? What about using an actual object instead?

Then you can store the info directly in NSArray without having to deal with NSData.

Or wrap the struct in an object if you have to use a struct.

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.
 
...
Code:
struct InfoAboutThingy {
   int info1;
   int info2;
   /* etc. */
};
...
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
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/
 
Last edited:
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.