2

I'm having trouble removing items from my NSMutableArray. I'm extremely new to Objective-C, so please bear with me.

So far, I have the following: I'm trying to remove a line from the array if it has certain text inside. I cannot do this while fast-enumerating, so I'm trying to store the index, for removal after the enumeration has finished. However, I'm being told that this makes a pointer from an integer without a cast. Confused!

//First remove any previous Offending entry.
//Read hostfile into array.
NSString *hostFileOriginalString = [[NSString alloc] initWithContentsOfFile:@"/etc/hosts"];
NSMutableArray *hostFileOriginalArray = [[hostFileOriginalString componentsSeparatedByString:@"\n"] mutableCopy];
NSInteger hostFileOffendingLocation;

//Use a for each loop to iterate through the array.
for (NSString *lineOfHosts in hostFileOriginalArray) {

    if ([lineOfHosts rangeOfString:@"Offending"].location != NSNotFound) {

    //Offending entry found, so remove it.
    //[hostFileOriginalArray removeObject:lineOfHosts];

    hostFileOffendingLocation = [hostFileOriginalArray indexOfObject:lineOfHosts];
    //NSLog(@"%@", hostFileOffendingLocation);
}

}
//Release the Array. 
[hostFileOriginalArray release];

//Remove offending entry from Array.
[hostFileOriginalArray removeObject:hostFileOffendingLocation];
4

3 回答 3

0
//Remove offending entry from Array.
[hostFileOriginalArray removeObjectAtIndex:hostFileOffendingLocation];

//Release the Array. 
[hostFileOriginalArray release];

您应该收到编译器警告...看看它们,它们通常很有帮助,我总是尝试发出 0 个警告...这样我就知道我在哪里做了粗心的事情。

于 2011-05-06T22:26:02.107 回答
0

My real question is why are you releasing your array before modifying it

try moving

[hostFileOriginalArray release];

to after

[hostFileOriginalArray removeObject:hostFileOffendingLocation];
于 2011-05-06T18:41:57.373 回答
0

您可以通过调用在没有循环的情况下执行此操作[hostFileOriginalArray removeObjectIdenticalTo:@"Offending"];

请注意,它将删除违规对象的多个实例,但这看起来就像您想要的那样。它还将以快速的方式执行操作,而您不必担心要使用哪个循环的实现细节。

作为一般规则(特别是对于真正常用的对象,如容器和 NSString),检查类引用以查看 Apple 是否已经有办法做你想做的事情。它使您的代码对其他 Cocoa 用户(包括未来的您)更具可读性,并减少了代码维护——您现在将其留给 Apple 来为他们的代码添加诸如快速枚举之类的新技术,并且当您链接时您可以免费获得它针对新版本的 SDK。

此外,您可能应该在函数末尾返回 hostFileOriginalArray,这样它可以做一些有用的事情——您可以将它作为自动释放的对象返回。

于 2011-05-06T18:42:55.347 回答