从 plist (UITableView) 中删除第一项时应用程序崩溃
想要从我的 UITableView 中删除行。 UITableview 从 plist 获取数据。因此,当我删除一行时,我告诉应用程序删除 plist 中的相应项目(在本例中是字典。字典的一项(名称)是 UITableViewCell 的标题,因此 plist 看起来像这样
Dictionary
KEY(Name)
ITEM
KEY(Description)
ITEM
Dictionary
KEY(name)
....
:) 我使用以下代码删除行,除了第一行之外,它工作正常。当我尝试删除第一行时,应用程序崩溃了,我不知道为什么。
int g = indexPath.row;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:@"data.plist"];
NSMutableArray *array = [[NSMutableArray alloc] initWithContentsOfFile:path];
[array removeObjectAtIndex:g];
[array writeToFile:path atomically:YES];
In want to delete rows from my UITableView. The UITableview gets it data from a plist. So when i delete a row i tell the app to delete the corresponding item in the plist (in this case a dictionary. One item of the dictionary (Name) is the title of the UITableViewCell, so the plist looks like so:
Dictionary
KEY(Name)
ITEM
KEY(Description)
ITEM
Dictionary
KEY(name)
....
)
And i use the following code to delete the rows, it works fine, apart from the very first row. The app crashes when i try to delete the first row, i have no idea why.
int g = indexPath.row;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:@"data.plist"];
NSMutableArray *array = [[NSMutableArray alloc] initWithContentsOfFile:path];
[array removeObjectAtIndex:g];
[array writeToFile:path atomically:YES];
EXC_BAD_ACCESS
通常意味着程序试图使用已经被释放的对象。我怀疑这样的对象可能是数组,因为当您尝试删除其第 0 个元素时,它刚刚被分配。您可以通过添加 NSLog 跟踪来轻松检查这一点,如下所示:
一般来说,为了确定可能是哪个对象,我的建议是启用 NSZombies。您可以通过使用“Zombies”性能工具运行应用程序来实现此目的 或 设置环境变量。
您将收到一条更具描述性的错误消息,该消息还将标识您尝试访问的对象的类型。
EXC_BAD_ACCESS
usually means that the program tried to use an object that had already been deallocated.I doubt that such object could be
array
, since it has just been allocated when you try and remove its 0-th element. You could easily check this by adding an NSLog trace like here:In general, to determine which object could be, my suggestion is enable
NSZombies
. You can do that by running the app using the "Zombies" performance tool, or setting an environment variable.You will get a much more descriptive error message that will also identify the type of object that you tried to access.