I have some numbers stored in an NSString.
Is it safe to extract them into an NSInterger like this :
NSString* path = [[NSBundle mainBundle] pathForResource:@"rugby" ofType:@"txt" inDirectory:@""];
NSString* data = [NSString stringWithContentsOfFile:path encoding: NSUTF8StringEncoding error: NULL];
NSMutableArray *statsHolder = [[NSMutableArray alloc] init];
[statsHolder addObject:[NSString [data substringWithRange:NSMakeRange(0, 3)] integerValue]];
Am i misunderstanding how to do this or would that be valid?
My second question is about objects. I am trying to copy objects. I am worried that if i copy an object into an array then later change the value contained in the object that was copied into the array, the object thats in the array will also have the value changed as it is just a pointer to the original object. I demo what i mean in code as its hard to make clear.
else if ([newString isEqualToString: newline])
{
[statsHolder addObject:[[data substringWithRange:NSMakeRange(i-rangeCount, rangeCount)] integerValue]];
commaCount=0;
rangeCount=0;
Card *myCard = [[Card alloc] init];
myCard.name = nameHolder;
myCard.information = infoHolder;
for (int x = 0; x < [statsHolder count]; x++)
{
[myCard.statsArray addObject:[statsHolder objectAtIndex:x]];
}
[deckArray addObject:myCard];
[myCard autorelease];
[statsHolder removeAllObjects];
}
You can see above I am filling an object called Card *mycard and then copying this into my NSMutableArray *deckArray.
NSString *nameHolder = @"";
NSString *infoHolder = @"";
NSMutableArray *statsHolder = [[NSMutableArray alloc] init];
Are my vars to hold the data while i collect it, before there is enough to populate the Card object and copy it into the array.
So my question is.. Will my all the Card objects stored in the array all point to the last values that were contained in
NSString *nameHolder = @"";
NSString *infoHolder = @"";
NSMutableArray *statsHolder = [[NSMutableArray alloc] init];
Because of the way arrays and pointers work?
Sorry for asking a big complicated question. 🙂
-Code
The
integerValuemethod is a perfectly fine way to convert a string to an integer. Another way, especially if you plan on storing multiple ints in a string (perhaps separated by a comma), isNSScanner.You need to wrap your number in some kind of object before putting it into an array.
NSNumberis designed for this:Finally, what happens when you set properties on your Card class depends on how you declared the properties or wrote the methods. When it comes to strings, it’s usually a good idea to copy them:
Now, when you
card.name = xyz, the card will store a copy ofxyz. If the original is modified or released, it won’t affect your card’s copy of the string.