can somebody please explain me the difference between the following code snippets for filling the myStrings array:
NSString *match = @"ad*.png";
NSString *bundleRoot = [[NSBundle mainBundle] bundlePath];
NSFileManager *fm = [NSFileManager defaultManager];
NSArray *dirContents = [fm contentsOfDirectoryAtPath:bundleRoot error:nil];
NSPredicate *fltr = [NSPredicate predicateWithFormat:@"SELF like %@", match];
NSArray *onlyPNGs = [dirContents filteredArrayUsingPredicate:fltr];
myStrings = [NSMutableArray array];
for(int i=0;i<[onlyPNGs count];i++)
{
[myStrings addObject:(NSString *)[onlyPNGs objectAtIndex:i]];
}
NSLog([myStrings description]);
When I fill my array this way, after the constructor, myStrings becomes null somehow but instead of filling with filter, if I add items manually everythings fine:
[myStrings addObject:@"adburgerking1.png"];
[myStrings addObject:@"adburgerking2.png"];
[myStrings addObject:@"adburgerking3.png"];
[myStrings addObject:@"addominos1.png"];
[myStrings addObject:@"admcdonalds1.png"];
[myStrings addObject:@"admcdonalds2.png"];
[myStrings addObject:@"admcdonalds3.png"];
[myStrings addObject:@"admeshuriskender1.png"];
[myStrings addObject:@"adquickchina1.png"];
[myStrings addObject:@"adsencam1.png"];
[myStrings addObject:@"adsultanahmetkoftecisi1.png"];
Thanks in advance!!!
From your first comment:
myStringsis a property withretainsemantics – a property will only retain a value if accessed as a property (self.myStrings = ...), if you directly assign to a underlying variable (myStrings = ...) there will be no retain.From your second comment:
[[NSMutableArray alloc] init]vs.[NSMutableArray array]–[[NSMutableArray alloc] init]returns an array you own, you don’tretainit to keep it; however[NSMutableArray array]returns an array you do not own, you mustretainit if you wish to keep it.So what you need is:
The RHS returns an array you do not own, the LHS will
retainit – now it will stay around.You might be tempted to use:
myStrings = [[NSMutableArray alloc] init];
as the RHS returns an array you own and the LHS just stores it without retaining it as you’re accessing the variable and not the property. However this version will not
releaseany previous array referenced bymyStringsso does not work in general.The rule is always access a property using dot notation, with the possible exception of a classes
initanddeallocmethods (this last bit is debated).