when i remove object from nsmutable array it shows exception but some time it works
[Array removeObjectAtIndex:row];
i have use this code
Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: '-[__NSCFArray removeObjectAtIndex:]: mutating method sent to immutable object'
Array is type of NSarray ... it is object of NSArray it should be object of NSMutableArray and not NSArray
Related
I am using UIManagedDocument with Parent Child context.
In my child context I do the following
Code 1
NSSet *results = [self.event.memberships filteredSetUsingPredicate:[NSPredicate predicateWithBlock:^BOOL(id evaluatedObject, NSDictionary *bindings) {
return ([[evaluatedObject deleted] boolValue] == NO);
}]];
Above code returns the expected results (only Not deleted members for the event).
Code 2
But this code does not. It fetches all records.
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"deleted == NO"];
NSSet *results = [self.event.memberships filteredSetUsingPredicate:predicate];
It seems confusing. Both should return same results, but predicateWithBlock returns correct results where as predicateWithFormat returns all records.
What are the pros and cons of using predicateWithBlock instead of predicateWithFormat?
The problem is that you have defined an attribute deleted for your entity. That conflicts with the isDeleted method of NSManagedObject, so you should rename that attribute.
The following "experiment" shows that strange things happen if you call your attribute "deleted" (c is a managed object with a custom deleted attribute):
// Set custom "deleted" property to YES:
c.deleted = #YES;
// Use the property, as your Code 1
NSLog(#"%#", [c deleted]);
// Output: 1
// Use Key-Value Coding, as your Code 2
NSLog(#"%#", [c valueForKey:#"deleted"]);
// Output: 0
// Now really delete the object and try again:
[context deleteObject:c];
NSLog(#"%#", [c valueForKey:#"deleted"]);
// Output: 1
Your "Code 1" refers to the property, therefore it returns the expected result. "Code 2" uses Key-Value Coding, and [c valueForKey:#"deleted"] returns YES if the object
actually has been deleted from the context!
So renaming that attribute should solve your problem. Unfortunately the compiler does not
emit warnings if an attribute name conflicts with a built-in method.
Use the formatting placeholder to replace the bool value:
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"%K == %#",
#"deleted", #(NO)];
Your use of the key path is probably ok, but the right-hand side probably doesn't look like "NO" to the parser.
I'm trying to add an object to an NSMutableArray with code like this:
Item *newItem = [[Item alloc] init];
[self.theArray addObject:newItem];
If I remember correctly, back in the old retain/release days I wouldn't have to worry about the newItem variable going out of scope, because the object would receive a retain when it was added to the array, and so wouldn't be deallocated.
But I'm using ARC now, and the object disappears. The array itself is fine, and the other objects it contained already are not affected. So I suspect that my newItem is being automatically deallocated for some reason.
Can someone give me an idea about what is going on here, and how I could fix it?
Item *newItem = [[Item alloc] init];
// This line is the same as this
//
// __strong Item *newItem = [[Item alloc] init];
//
// the newItem variable has strong reference of the Item object.
// So the reference count of the Item object is 1.
[self.theArray addObject:newItem];
// Now theArray has strong reference of the Item object.
// So the reference count of the Item object is 2.
The reference count of the Item object is 2, thus the Item object will not be released. If your code had a scope like the following,
{
Item *newItem = [[Item alloc] init];
[self.theArray addObject:newItem];
}
It doesn't affect the Item object.
{
Item *newItem = [[Item alloc] init];
[self.theArray addObject:newItem];
// the reference count of the Item object is 2 as I said.
}
// The scope of the newItem variable was ended.
// So the lifetime of the newItem variable was ended,
// then the strong reference by the newItem was gone.
// Thus the reference count of the Item object was reduced from 2 to 1.
The reference count of the Item object is 1, thus the Item object will not be released as well.
I finally found out what was wrong. It had nothing to do with allocations. What was happening was the awakeFromNib method was being called again when a table view was being reloaded. Of course that reset all kinds of things, making stuff disappear.
How do I sort my fetched results by a value that is returned by a method in a category of the entity I'm fetching?
In my category, I sum up several values from the entity's to-many relationship, then divide by the number of objects in the relationship, effectively creating an average that I return in my category method as a float value.
Here is my code:
In the Category.h
- (float)smallPenaltyAvg;
In the Category.m
- (float)smallPenaltyAvg{
float smallPenaltyAvg = 0;
for (Match *mtch in self.matches) {
smallPenaltyAvg += [mtch.penaltySmall floatValue];
}
if ([self.matches count] > 0) {
smallPenaltyAvg = (float)smallPenaltyAvg/(float)[self.matches count];
}
return smallPenaltyAvg;
}
And when I call it in the Core Data Table View Controller class that I created...
NSFetchRequest *poolRequest = [[NSFetchRequest alloc] initWithEntityName:#"Team"];
poolRequest.predicate = [NSPredicate predicateWithFormat:#"regionalIn.name = %#", _regionalToDisplay];
poolRequest.sortDescriptors = #[[NSSortDescriptor sortDescriptorWithKey:#"smallPenaltyAvg" ascending:YES]];
And I have the Category.h file imported on every file previously mentioned outside of the Category.h file itself.
It gives me the error of:
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'keypath smallPenaltyAvg not found in entity <NSSQLEntity Team id=5>
Am I not allowed to do this?
If I am, what am I doing wrong?
I do not think this has anything to do with the kind of persistent store.
The trick is to create an appropriate attribute in the managed object model, and mark it as Transient. Then override the getter of this attribute to do your calculations.
Now your fetch request should work as expected (although there are some caveats with fetched results controllers).
As for the SQLite problem, when you add the SQLite store with
- (NSPersistentStore *)addPersistentStoreWithType:(NSString *)storeType
configuration:(NSString *)configuration
URL:(NSURL *)storeURL
options:(NSDictionary *)options
error:(NSError **)error
just pass NSSQLiteStoreType as the storeType. The other options are binary and in-memory, so in this sense this is indeed the "default".
This is not possible when using a backing SQLite store.
My suggestion is you persist the average property, and maintain it yourself by overriding the Match setCategory: property and making the calculation there for every match added.
What I did to solve my problem was create a new attribute for every average or sum that I needed in the Team object from all of its Match objects' attributes and then created a method in the TeamCategory file that populated those averages and that method was called every time a Match object was inserted into the Team object. It took a while to do, but it works now. If there is a better solution, I'm still open for suggestions.
I have the following block of codes in my program.
for(int k=0;k<reqroom.count;k++)
{
NSString *rent=[roomRent objectAtIndex:k];
NSString *tax=[roomTax objectAtIndex:k];
NSString *no=[textvaluearray objectAtIndex:k];
NSDecimalNumber *rentd=[NSDecimalNumber decimalNumberWithString:rent];
}
//here roomRent,roomTax and textvaluearray are NSMutableArrays
This is the error that I am receiving:
'NSInvalidArgumentException', reason: '-[__NSArrayI length]: unrecognized selector sent to instance 0x81b2ce0'
Thanks in advance.
From the exception "-[__NSArrayI length]:" it looks like "rent" object is not a string type and its array. Can you check the type of "rent" before converting to decimal.
What is reqroom? Is it an NSString or NSArray (or NSMutableArray)? If it's some sort of array and you want to iterate as many times as there are objects in the array, you should probably do something like
for(int k=0;k<[reqroom count];k++)
I have a CoreData model that looks a bit like this:
Object A:
Results -- A one to many relationship to an indeterminate number of Object B's.
Object B:
Object Name -- A string. (potentially not unique)
Parent -- A singular relationship with Object A.
I am struggling with writing a NSPredicate that will return ObjectB if I know a given Object A and the Object Name string I am looking for. I have tried the following, but always get this error:
"'NSInvalidArgumentException', reason: 'Unable to parse the format string ..."
request.predicate = [NSPredicate predicateWithFormat:#"NameString == %#, SELF IN %#", NameString, ObjectA.results];
request.predicate = [NSPredicate predicateWithFormat:#"(NameString == %#) IN %#", NameString, ObjectA.results];
And so on...
This seems like this should be a simple and obvious thing to do, but I am new at Core Data and am having trouble finding an example that shows this.
Thanks!
You need to use %K.
You may need something like this in your predicate
NSString enitity=#"ObjectA";
NSString attribute=#"results";
request.predicate = [NSPredicate predicateWithFormat:#"NameString == %#, SELF IN %K.%K", NameString, enitity,attributes];
Look here.