Array value replacement from array within array in iPhone - nsmutablearray

I have array output like this.
{
id = 1;
user = {
name="ABC"
}
},
{
id = 2;
user = {
name="XYZ"
}
},
I have to change id with number 5 and 6 and name with "asd" and "fgh". My array definition is here.
myArray=[[NSMutableArray alloc]initWithArray:statuses];
And here is my approach for chaning of "id".
[[myArray objectAtIndex:0]replaceObjectAtIndex:0 withObject:#"5"];
[[myArray objectAtIndex:0]replaceObjectAtIndex:0 withObject:#"6"];
But I am getting following acception.
[__NSCFDictionary replaceObjectAtIndex:withObject:]: unrecognized selector sent to instance 0x6511810
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFDictionary replaceObjectAtIndex:withObject:]: unrecognized selector sent to instance 0x6511810'

myArray seems to be NSArray which is Immutable.
How did you declare myArray?
EDIT:
First:
myArray = [statuses mutableCopy];
Second:
[[myArray objectAtIndex:0] setObject:#"5" forKey:#"id"];
[[myArray objectAtIndex:1] setObject:#"6" forKey:#"id"];
[[[myArray objectAtIndex:0] objectForKey:#"user"] setObject:#"asd" forKey:#"name"];
[[[myArray objectAtIndex:1] objectForKey:#"user"] setObject:#"fgh" forKey:#"name"];

Related

coreData returning only one result

Having this weird issue, No matter what predicate I apply its only returning one result, and if I don't add any predicate its returns all the rows of the table, what I want is only return the rows with matching progIds
I have the list of programIds and based on that I want to search in TvInfo table.
.......
......
progId = [Int64(3211),Int64(16844)] // hardcored ids from tvInfo table
let tvInfoRequest: NSFetchRequest<TvInfo> = TvInfo.fetchRequest()
tvInfoRequest.predicate = NSPredicate(format: "progId == %i", argumentArray: progId)
tvInfoRequest.returnsDistinctResults = true
tvInfoRequest.resultType = .managedObjectResultType
var tvShows = [TvInfo]()
coreDataStack.managedObjectContext.performAndWait({
do{
let tvInfoResult = try self.coreDataStack.managedObjectContext.fetch(tvInfoRequest)
tvShows = tvInfoResult
} catch {
fatalError("Error fetching channels displayShow")
}
})
I thought maybe some issue with progId (type mismatch Int64), so I tried fetching using the tvShow name (with exact showNames from tvInfo table still getting only one result, (first name passed in the array)
tvInfoRequest.predicate = NSPredicate(format: "progName MATCHES %#", argumentArray: ["Supercar Superbuild","Kanahiya Bhaiya Live"])
weird thing is I used the same logic to fetch progIds from channels Table and its working fine(getting progId with exact matches) and its working for other tables also like channel Id fetching from channel tables
// fetching progIds from channel table
let tvScheduleRequest: NSFetchRequest<TvSchedule> = TvSchedule.fetchRequest()
tvScheduleRequest.predicate = NSPredicate(format: "chId == %i", argumentArray: channelIds)
tvScheduleRequest.returnsDistinctResults = true
var progId = [Int64]()
coreDataStack.managedObjectContext.performAndWait({
do{
let tvScheduleResult = try self.coreDataStack.managedObjectContext.fetch(tvScheduleRequest)
if tvScheduleResult.count > 0 {
for array in tvScheduleResult {
progId.append(array.progId)
}
}
} catch {
fatalError("Error fetching channels to display show")
}
})
PS:
Its returning 1 row so it's not an issue of context, wrong key,
thread
there are data in table as if I don't apply any predicate its
returning 100+ rows
I am using argumentArray for predicate, not single args CVarArg.
Thanks for help
In predicate try using %# instead of %i.
tvInfoRequest.predicate = NSPredicate(format: "progId == %i", argumentArray: progId).
One more thing check the variable that you are passing to predicate progId.

Xpages - Exception occurred calling method NotesView.getNextDocument(lotus.domino.local.Document) null

I'm getting the above error.
Is there a way I can check if next document is null?
Below is my code:
var vec:NotesView = database.getView("QueryNotes");
var queryColl:NotesDocumentCollection = vec.getAllDocumentsByKey(ProjectUNID,true);
if(queryColl.getCount() > 0){
var queryDoc1:NotesDocument = queryColl.getFirstDocument();
while (queryDoc1 != null) {
if(!queryDoc1.hasItem("QueryEndDate")){
queryDoc1.appendItemValue("QueryEndDate", session.createDateTime(#Now()));
var tmpdoc = vec.getNextDocument(queryDoc1); //error when next is null, or does not exist
queryDoc1.recycle();
queryDoc1 = tmpdoc;
}
}
}
There should be a way of checking, a similar question on stackoverflow did not answer the question.
Looking forward to your response.
You are calling getNextDocument() on the vec variable (which is a view object and doesn't have that method). You should use the queryColl variable instead.

Need help filtering core data in Swift 3

I can't seem to find any good documentation or tutorials that pertain to filtering core data in Swift 3.
I have the following code:
let tempVar: String = "abcdef"
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
do {
/* Need code to modify the fetchRequest, so that it only pulls results where the "projectID" field is equal to whatever is stored in the tempVar variable. */
cstProjectDetails = try context.fetch(CSTProjectDetails.fetchRequest())
} catch {
print("There was an error fetching CST Project Details.")
}
Basically, I am just trying to do add a simple filter to the fetchRequest, so that it only pulls results from "cstProjectDetails" where the "projectID" field is equal to the contents of a previously set variable (in this case, "tempVar").
Any ideas?
Edit: The checked answer did the trick for me, but I had to make a quick adjustment to the code for the request initializer. Here is the code that I ended up with:
do {
let request: NSFetchRequest<CSTProjectDetails> = CSTProjectDetails.fetchRequest()
request.predicate = NSPredicate(format: "projectID == %#", cstProjectID)
cstProjectDetails = try context.fetch(request)
print(cstProjectDetails)
} catch {
print("There was an error fetching CST Project Details.")
}
You need a predicate attached to the request:
let request = CSTProjectDetails.fetchRequest()
request.predicate = NSPredicate(format: "projectID == %#", tempVar)
cstProjectDetails = try context.fetch(request)

Restkit + Core Data: Inserts duplicate values in a UITableView on every app launch

Following AlexEdge Tutorial I have encountered the following behavior. I can provide code as requested since there are many lines and I'm not really sure where to look. Basically, it "works" in the sense that the data is properly loaded into the UITableView, but after stopping and starting up the simulator, it inserts new duplicate rows in each section.
I figured this would have something to do with caching but I am following the above tutorial pretty closely and I've set the identificationAttributes to identify unique records (wouldn't, for example, adding ALL attributes effectively eliminate the possibility that I've not specified a sufficiently unique key, just for debugging purposes?). I've tried changing the Cache name, setting it nil, but it keeps inserting duplicates. Every so often I reset the simulator just to start on a clean slate.
If it matters, I am calling getObjectsAtPath in viewDidLoad as per the tutorial. My understanding of how RestKit worked was that it was okay to do so because it would be smart enough to infer that no updates were necessary as the records are all the same.
Edit
I have set identificationAttributes to an array of two integer attributes that really do determine a unique record.
I also have a managedObjectCache:
// Seal the deal
[managedStore createPersistentStoreCoordinator];
NSString *storePath = [RKApplicationDataDirectory() stringByAppendingPathComponent:#"CCTDB.sqlite"];
NSError *error;
NSPersistentStore *persistentStore =
[managedStore
addSQLitePersistentStoreAtPath:storePath
fromSeedDatabaseAtPath:nil
withConfiguration:nil
options:#{
NSMigratePersistentStoresAutomaticallyOption:#YES,
NSInferMappingModelAutomaticallyOption:#YES
}
error:&error];
NSAssert(persistentStore, #"Failed to add persistent store with error: %#", error);
[managedStore createManagedObjectContexts];
managedStore.managedObjectCache = [[RKInMemoryManagedObjectCache alloc] initWithManagedObjectContext:managedStore.persistentStoreManagedObjectContext];
EDIT 1
Here is the log output of the second time around
(2013-07-11 03:18:29.961 cocoaclinical[18773:3d07] D restkit.object_mapping:RKPropertyInspector.m:130 Cached property inspection for Class 'EMDisease': {
diseaseId = {
isPrimitive = 0;
keyValueCodingClass = NSNumber;
name = diseaseId;
};
diseaseIdValue = {
isPrimitive = 1;
keyValueCodingClass = NSNumber;
name = diseaseIdValue;
};
name = {
isPrimitive = 0;
keyValueCodingClass = NSString;
name = name;
};
subDiseaseId = {
isPrimitive = 0;
keyValueCodingClass = NSNumber;
name = subDiseaseId;
};
subDiseaseIdValue = {
isPrimitive = 1;
keyValueCodingClass = NSNumber;
name = subDiseaseIdValue;
};
}
2013-07-11 03:18:29.975 cocoaclinical[18773:3f03] I restkit.core_data:RKInMemoryManagedObjectCache.m:94 Caching instances of Entity 'EMDisease' by attributes 'diseaseId, subDiseaseId'
2013-07-11 03:18:29.983 cocoaclinical[18773:3f03] T restkit.core_data:RKInMemoryManagedObjectCache.m:127 Cached 31 objects
2013-07-11 03:18:29.984 cocoaclinical[18773:3f03] D restkit.object_mapping:RKMapperOperation.m:231 Asked to map source object {
DiseaseSystemIdMember = 161;
DisplayNameMember = "Acute Lymphocytic Leukemia";
SubDiseaseSystemIdMember = 1886;
} with mapping <RKEntityMapping:0x96c2850 objectClass=EMDisease propertyMappings=(
"<RKAttributeMapping: 0x96ba060 SubDiseaseSystemIdMember => subDiseaseId>",
"<RKAttributeMapping: 0xb58df40 DisplayNameMember => name>",
"<RKAttributeMapping: 0xb58df70 DiseaseSystemIdMember => diseaseId>"
)>
2013-07-11 03:18:29.984 cocoaclinical[18773:3f03] D restkit.object_mapping:RKMappingOperation.m:952 Starting mapping operation...
2013-07-11 03:18:29.985 cocoaclinical[18773:3f03] T restkit.object_mapping:RKMappingOperation.m:953 Performing mapping operation: <RKMappingOperation 0xb5b7820> for 'EMDisease' object. Mapping values from object {
DiseaseSystemIdMember = 161;
DisplayNameMember = "Acute Lymphocytic Leukemia";
SubDiseaseSystemIdMember = 1886;
} to object <EMDisease: 0xb5b7ee0> (entity: EMDisease; id: 0xb5b7f80 <x-coredata:///EMDisease/t8DD8EE18-C798-468F-9E03-C6A3C724AA772> ; data: {
diseaseId = 161;
name = nil;
subDiseaseId = 1886;
}) with object mapping (null)
2013-07-11 03:18:30.027 cocoaclinical[18773:3f03] T restkit.object_mapping:RKMappingOperation.m:550 Mapping attribute value keyPath 'SubDiseaseSystemIdMember' to 'subDiseaseId'
2013-07-11 03:18:30.028 cocoaclinical[18773:3f03] T restkit.object_mapping:RKMappingOperation.m:583 Skipped mapping of attribute value from keyPath 'SubDiseaseSystemIdMember to keyPath 'subDiseaseId' -- value is unchanged (1886)
2013-07-11 03:18:30.029 cocoaclinical[18773:3f03] T restkit.object_mapping:RKMappingOperation.m:550 Mapping attribute value keyPath 'DisplayNameMember' to 'name'
2013-07-11 03:18:30.029 cocoaclinical[18773:3f03] T restkit.object_mapping:RKMappingOperation.m:572 Mapped attribute value from keyPath 'DisplayNameMember' to 'name'. Value: Acute Lymphocytic Leukemia
2013-07-11 03:18:30.030 cocoaclinical[18773:3f03] T restkit.object_mapping:RKMappingOperation.m:550 Mapping attribute value keyPath 'DiseaseSystemIdMember' to 'diseaseId'
2013-07-11 03:18:30.030 cocoaclinical[18773:3f03] T restkit.object_mapping:RKMappingOperation.m:583 Skipped mapping of attribute value from keyPath 'DiseaseSystemIdMember to keyPath 'diseaseId' -- value is unchanged (161)
2013-07-11 03:18:30.031 cocoaclinical[18773:3f03] D restkit.object_mapping:RKMappingOperation.m:1021 Finished mapping operation successfully...
You do need to set identificationAttributes, generally only one or two attributes though, not everything. Your entities should have some unique identifier.
You also want to add a managedObjectCache to your managed object store. This is the part that allows RestKit to match objects using your identificationAttributes and update the existing items instead of creating new ones.

Restkit mapping empty json list with relationship

I've got a problem with empty json list mapping, I've got a JSON response that look this way :
{
id = 1;
image = "http://image.com/image.png";
name = "Test Category #1";
"restricted_position" = 0;
"restricted_time" = 0;
restrictions = {
"restricted_position_detail" = (
);
"restricted_time_detail" = (
);
}
The mapping for the class look like this :
+(RKManagedObjectMapping *)getObjectMapping
{
RKObjectRelationshipMapping *restrictionMapping = [RKObjectRelationshipMapping mappingFromKeyPath:#"restrictions" toKeyPath:#"restrictions" withMapping:[Restriction getObjectMapping]];
RKManagedObjectMapping *mapping = [RKManagedObjectMapping mappingForClass:[PLCategory class] inManagedObjectStore:[RKObjectManager sharedManager].objectStore];
[mapping mapKeyPath:#"id" toAttribute:#"identifiant"];
[mapping mapKeyPath:#"name" toAttribute:#"name"];
[mapping mapKeyPath:#"image" toAttribute:#"imageUrl"];
[mapping mapKeyPath:#"restricted_position" toAttribute:#"restricted_position"];
[mapping mapKeyPath:#"restricted_time" toAttribute:#"restricted_time"];
[mapping addRelationshipMapping:restrictionMapping];
[mapping setPrimaryKeyAttribute:#"identifiant"];
return mapping;
}
The mapping for the Restriction class :
+(RKManagedObjectMapping *)getObjectMapping
{
RKObjectRelationshipMapping *zg_mapping = [RKObjectRelationshipMapping mappingFromKeyPath:#"restricted_time_detail" toKeyPath:#"restricted_time_detail" withMapping:[GeographicalArea getObjectMapping]];
RKObjectRelationshipMapping *ph_mapping = [RKObjectRelationshipMapping mappingFromKeyPath:#"restricted_position_detail" toKeyPath:#"restricted_position_detail" withMapping:[TimeSlot getObjectMapping]];
RKManagedObjectMapping *mapping = [RKManagedObjectMapping mappingForClass:[Restriction class] inManagedObjectStore:[RKObjectManager sharedManager].objectStore];
[mapping addRelationshipMapping:zg_mapping];
[mapping addRelationshipMapping:ph_mapping];
return mapping;
}
No matter what I try I keep getting these annoying errors :
Core Data Save Error
NSLocalizedDescription: The operation couldn’t be completed. (Cocoa error 1580.)
NSValidationErrorKey: restricted_position_detail
NSValidationErrorPredicate: (null)
NSValidationErrorObject:
<Restriction: 0xb9c2f20> (entity: Restriction; id: 0xb9b5d90 <x-coredata:///Restriction/tE6CDEA6C-5A2A-48AE-9454-A8E6CC35F5078> ; data: {
category = "0xb9b67b0 <x-coredata:///PLCategory/tE6CDEA6C-5A2A-48AE-9454-A8E6CC35F5077>";
"restricted_position_detail" = (
);
"restricted_time_detail" = (
);
})
2013-07-08 12:39:00.716 [7442:28513] E restkit.core_data:RKManagedObjectStore.m:263 Core Data Save Error
NSLocalizedDescription: The operation couldn’t be completed. (Cocoa error 1580.)
NSValidationErrorKey: restricted_time_detail
NSValidationErrorPredicate: (null)
NSValidationErrorObject:
<Restriction: 0xb9c2f20> (entity: Restriction; id: 0xb9b5d90 <x-coredata:///Restriction/tE6CDEA6C-5A2A-48AE-9454-A8E6CC35F5078> ; data: {
category = "0xb9b67b0 <x-coredata:///PLCategory/tE6CDEA6C-5A2A-48AE-9454-A8E6CC35F5077>";
"restricted_position_detail" = (
);
"restricted_time_detail" = (
);
})
What I'd like to do is map these empty list with an empty NSArray. Does anyone have a clue how to do that ? is it even possible ?
The problem is that you have made the relationships non-optional. By default they will be empty sets (not arrays), but if you try to save when the sets are empty you will get validation errors because you configured that the relationships have to have at least one connection (that's what non-optional means).
If you want to allow zero connections, make the relationships optional.
Note that you might wan't to make the other end of the relationships non-optional, so you know if you have a GeographicalArea or TimeSlot then it must be connected to a Restriction. This would usually tie in with a Cascade deletion rule.

Resources