PDA

View Full Version : Unconstization




Miglu
Jun 19, 2011, 03:44 AM
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?



jiminaus
Jun 19, 2011, 03:53 AM
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:

struct InfoAboutThingy {
int info1;
int info2;
/* etc. */
};


Use instead:

@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:

@interface InfoAboutThingyHolder : NSObject {
@public
InfoAboutThingy infoAboutThingy;
}
@end

@implementation InfoAboutThingyHolder
@end

Sydde
Jun 19, 2011, 09:50 AM
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.

chown33
Jun 19, 2011, 01:05 PM
...

struct InfoAboutThingy {
int info1;
int info2;
/* etc. */
};

...
EDIT: Or wrap the struct in an object if you have to use a struct. For example:

@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:

@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/