I have an NSMutable array like this
`
mutablearray
{
"colour_id" = 1,
"day_id" = "2011-01-01 00:00:00 +0000"
},
{
"colour_id" = 2,
"day_id" = "2011-05-06 00:00:00 +0000"
},
`
I want to search whether 2011-05-06 00:00:00 +0000 this particular date is available or not in the NSMutableArray. How can I perform the search for this in ios. Please help me.
Thanks
The proper way of doing it is to convert each day_id value into an NSDate object and call [NSDate compare] to see if it's equal, however you can cheat and simply compare the strings, if you are sure they will always appear in this format:
NSArray *yourArray = ...;
NSString *colourId = nil;
for (NSDictionary *dict in yourArray) {
if ([dict[#"day_id"] isEqualToString:#"2011-05-06 00:00:00 +0000"]) {
colourId = dict[#"colour_id"];
break;
}
}
NSLog(#"Colour is %#", colourId);
Related
Any help would be great. Core Data is using "Date" for both due date and due time. Values are from Swift UI picker (displayedComponents: .date) and (displayedComponents: .hourAndMinute). It doesn't sort correctly.
var fetchCategories = [Category]()
let request: NSFetchRequest<Category> = Category.fetchRequest()
let predicate = NSPredicate(format: "isComplete == 0")
let sortDueDate = NSSortDescriptor(key: "dueDate", ascending: true)
let sortDueTime = NSSortDescriptor(key: "dueTime", ascending: false)
let sortDescriptors = [sortDueDate, sortDueTime]
request.sortDescriptors = sortDescriptors
request.predicate = predicate
do {
fetchCategories = try moc.fetch(request)
} catch {
print("Error fetching categories \(error.localizedDescription)")
}
return fetchCategories
A Date attribute in Core Data stores both date and time. I am guessing the dueTime attribute contains a date that is after the dueDate date, causing the sort issues.
The solution is to store the dueDate as just one attribute. This attribute contains both a date and a time, which you can modify separately in your user interface. You only need one SortDescriptor, too.
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.
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)
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.
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"];