我有一个自定义的NSManagedObject
,它有几个属性。我 alloc
和 init
对象的两个实例:compare1
和 compare2
。然后,我执行 NSFetchRequest
来获取其中两个自定义对象,并将它们的属性填充到 NSArray
结构中,以便稍后在 UITableView
中显示它们。
我的问题是,UITableView
崩溃了。我对代码做了一些研究,发现有时数组没有完整的计数。当我使用 slider 和文本字段时,它有时会起作用,但它(至少对我来说)不可重现。
提前谢谢您!
编辑:问题现在很清楚了。 对象描述
已完成。我通过 NSArray * array = [[NSArray alloc] initWithObjects: object.value1, ..., nil];
将其传输到 NSArray
。现在奇怪的是:[array count]
给了我一个错误的数字?只有 != 0
的值位于数组中。为什么这样?谢谢!
这是NSFetchRequest
的代码:
-(NSArray *)performFetch
{
if (__managedObjectContext == nil)
{
__managedObjectContext = [(MasterViewController *)[[UIApplication sharedApplication] delegate] managedObjectContext];
}
NSError *error = nil;
NSManagedObjectContext *context = [self managedObjectContext];
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Entity" inManagedObjectContext:context];
[fetchRequest setEntity:entity];
NSArray *fetchedObjects = [context executeFetchRequest:fetchRequest error:&error];
NSLog(@"FetchedObjects Count: %i", [fetchedObjects count]); //always right
compare1 = [fetchedObjects objectAtIndex:0]; //compare is a custom NSObject
compare2 = [fetchedObjects objectAtIndex:1]; //with several properties (.1 to .17)
NSLog(@"%@",[compare1 description]); //is complete
NSLog(@"%@",[compare2 description]); //is complete
NSArray * valuesS1 = [[NSArray alloc] initWithObjects:compare1.1,__andsoon__compare1.14, nil];
NSArray * valuesB1 = [[NSArray alloc] initWithObjects:compare1.14__andsoon__compare1.17, nil];
NSArray * valuesS2 = [[NSArray alloc] initWithObjects:compare2.1,__andsoon__compare2.14, nil];
NSArray * valuesB2 = [[NSArray alloc] initWithObjects:compare2.14__andsoon__compare2.17, nil];
NSMutableArray * valuesArray1 = [[NSMutableArray alloc] initWithObjects:valuesS1, valuesB1, nil];
NSMutableArray * valuesArray2 = [[NSMutableArray alloc] initWithObjects:valuesS2, valuesB2, nil];
compareArray = [[NSMutableArray alloc] initWithObjects:valuesArray1, valuesArray2, nil];
NSLog(@"Array1 count: %i",[values1 count]); //sometimes (I don't know why)
NSLog(@"Array2 count: %i",[values2 count]); //[values1 count] != [values2 count]
return compareArray; //sometimes returns an array with too less objects so my UITableView crashes
最佳答案
Only the values which are != 0 are in the array
您无法将 nil
值直接添加到数组中。 (nil
通常为零。)如果需要向数组添加“空”值,则需要检查并插入 NSNull
值。例如:
NSArray * valuesS1 = [[NSArray alloc] initWithObjects:val1 ? val1 : [NSNull null], val2 ? val2 : [NSNull null], nil];
编辑
?:
相当于:
if (val1) {
return val1;
}
else {
return [NSNull null];
}
如果你想使用@"0"
而不是NSNull
,你可以;它可以是任何你喜欢的东西,只要它是一个对象并且不是 nil
。
关于ios - 用 NSFetchRequest => [数组计数] 错误填充 NSArray,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8399463/