Sunday, March 15, 2009

assignment from distinct Objective-C type

If you want to overwrite the contents of an Objective C object, you might be tempted to do something like the following:

wordarray = [[NSMutableArray alloc] init];
... interesting things here ...
wordarray = [sentence componentsSeparatedByString:@" "];


You'll find that the second line there gets an enigmatic message "warning:assignment from distinct Objective-C type". If you ignore the message and run the code, everything runs fine so what's the problem? Well, you're stamping all over Objective-C's memory allocation and garbage collection, so at some point in the future, when you're least expecting it, your program will crash dramatically. The safe way to refine the contents of an object is by using a setXXXX: message:

[wordarray setArray:[sentence componentsSeparatedByString:@" "]];

No comments:

Post a Comment