I am trying to convert (or copy?) a NSString into a NSMutableArray. I guess my problem is that I don't really understand the structure of a MutableArray. In my limited knowledge, an Array could look like this:
NoteBook = [[NSMutableArray alloc] init];
for (int temp = 0; temp < 3; temp++) {
开发者_运维知识库 [NoteBook insertObject:@"Page" atIndex:temp];
}
Which would give me an Array of PagePagePage. Let's assume I wanted to open a txt file which contains PagePagePage, but the words were separated by a defined string so that I can keep the individual objects in my array apart, like so: Page--- end of page ---Page--- end of page ---Page.
Now, my next step would be to read this information from the txt file:
NSString *tempTextOut = [NSString stringWithContentsOfFile:filePath
encoding:NSUTF8StringEncoding
error:&error];
NoteBook = [tempTextOut componentsSeparatedByString: @"\n--- end of page ---\n"];
However, the last line does not work and I'm told by xCode: Incompatible Objective-C types assigning 'struct NSArray*', expected 'struct NSMutableArray*'. I don't really understand this - NSArray and MutableArray should be compatible (as one is the subclass of the other). Shouldn't xCode tell me that the problem is that I've been trying to convert a NSString into an NSMutableArray?
Would I perhaps need to re-set my MutableArray before putting something back into it, because right now, it still contains PagePagePage which I have assigned to it in the first step. I thought my NoteBook mutable array would simply be replaced by the string, but I guess that won't be the case.
I'd very much appreciate any help in this matter. Thanks!
componentsSeparatedByString:
returns a plain immutable NSArray, not an NSMutableArray. You can pass the array to [NSMutableArray arrayWithArray:]
or use mutableCopy
on the array to get a mutable array from it, or you can use addObjectsFromArray:
on an existing NSMutableArray to add objects to it.
If you go the mutableCopy
route, do remember that you are responsible for calling release
or autorelease
on it.
Assigning a mutable object to the same immutable type will lead to runtime errors if you want to manipulate the immutable instance.
You can get your mutable copy by calling:
NoteBook = [[tempTextOut componentsSeparatedByString: @"\n--- end of page ---\n"] mutableCopy];
If NoteBook is a retained property you should assign to it this way:
self.NoteBook = [[[tempTextOut componentsSeparatedByString: @"\n--- end of page ---\n"] mutableCopy] autorelease];
so the mutable copy doesn't get over retained. You can release in your dealloc method then as normal.
精彩评论