I have an NSArray loaded with objects (see below). I need to load these into a tableview based on which indexpath.row is clicked from another tableview.
If a user selects indexpath.row = 0, then the second tableview is reloaded with ORDER_CODE's which contain only GROUP = 0.
If the user selects indexpath.row = 1, then the second tableview is reloaded with ORDER_CODE's which contain only GROUP = 1.
Anyone have any advice/coding on how I can search thru the array and display the relevant data into the second tableview?
array=(
{
GROUP = 0;
"ORDER_CODE" = 410;
"PROD_DESCR" = "cement";
id = 0;
},
{
GROUP = 0;
"ORDER_CODE" = 411;
"PROD_DESCR" = "concrete";
id = 1;
},
{
GROUP = 1;
"ORDER_CODE" = 405;
"PROD_DESCR" = "asphalt";
id = 2;
})
Try the following code to filter the results (on clicking a particular tablerow) from the given array
NSArray *array; //your data array
//create a search predicate to filter the array
NSPredicate *searchPredicate = [NSPredicate predicateWithBlock:^BOOL(NSDictionary * evaluatedObject, NSDictionary *bindings) {
BOOL isValidGroup = [evaluatedObject[#"GROUP"] integerValue] == indexPath.row;
return isValidGroup;
}];
NSArray *filteredArray = [array filteredArrayUsingPredicate:searchPredicate]; //this is the filtered array you can use for the displaying in the table
Related
I'm Trying reorder UICollectionViewcell Images on drag and drop using RealmSwift As database, My UI is not updating on a drag and drop and strange behaviour, some Images are duplicating , my code is Like this
RealmModel As
class StoryAlbumDM: Object {
dynamic var id = 0
dynamic var type = ""
dynamic var isImage: Int = 0
dynamic var textData = ""
dynamic var imageData: NSData? = nil
dynamic var rowId: Int = 0
dynamic var position: Int = 0
dynamic var storyId: Int = 0
dynamic var isCoverImage: Int = 0
dynamic var imagePath = ""
let allStories = List<StoryAlbumDM>()
}
On drag and drop I'm doing Like this
func collectionView(collectionView: UICollectionView, atIndexPath: NSIndexPath, didMoveToIndexPath toIndexPath: NSIndexPath) {
print("moveItemAtIndexPath")
let fromIndexPath: Int = atIndexPath.row
print("from", fromIndexPath)
let toIndexPathInt: Int = toIndexPath.row
print("To", toIndexPath)
let fromData: StoryAlbumDM!
fromData = realm.objects(StoryAlbumDM.self).filter("position = %d AND storyId = %d", fromIndexPath, self.storyID).first!
let toData: StoryAlbumDM!
toData = realm.objects(StoryAlbumDM.self).filter("position = %d AND storyId = %d", toIndexPath, self.storyID).first!
var tempData = StoryAlbumDM()
self.performSelectorOnMainThread(#selector(StoryViewController.updateSrtoryInRealm), withObject: self.collectionView, waitUntilDone: true)
dispatch_async(dispatch_get_main_queue(), {
self.collectionView.performBatchUpdates({
self.collectionView.reloadData()
}, completion: nil)
})
}
func updateSrtoryInRealm() {
self.tempData.type = self.toData.type
self.tempData.isImage = self.toData.isImage
self.tempData.textData = self.toData.textData
self.tempData.rowId = self.toData.rowId
self.tempData.imageData = self.toData.imageData
self.tempData.position = self.toData.position
self.tempData.storyId = self.toData.storyId
self.tempData.isCoverImage = self.toData.isCoverImage
self.tempData.imagePath = self.toData.imagePath
do {
try! realm.write {
self.toData.type = self.fromData.type
self.toData.isImage = self.fromData.isImage
self.toData.textData = self.fromData.textData
self.toData.rowId = self.fromData.rowId
self.toData.imageData = self.fromData.imageData
self.toData.position = self.fromData.position
self.toData.storyId = self.fromData.storyId
self.toData.isCoverImage = self.fromData.isCoverImage
self.toData.imagePath = self.fromData.imagePath
// title.id = temp.id
self.fromData.type = self.tempData.type
self.fromData.isImage = self.tempData.isImage
self.fromData.textData = self.tempData.textData
self.fromData.rowId = self.tempData.rowId
self.fromData.imageData = self.tempData.imageData
self.fromData.position = self.tempData.position
self.fromData.storyId = self.tempData.storyId
self.fromData.isCoverImage = self.tempData.isCoverImage
self.fromData.imagePath = self.tempData.imagePath
}
//}
}
catch {
print("Printed error : ")
}
Problem: Images Are duplicating, Not updating on UI , Reorder strange behaviour, please help me on this
I answered a similar question recently, but I'll re-explain it here. :)
Easily, the best and quickest way to re-order Realm objects inside a Realm file is to make an overarching List object that holds all of the Realm objects of a given type.
For example in this case, you make another object to hold that allStories value you already created:
// Model class that manages the ordering of story album objects
class StoryAlbumDMList: Object {
let allStories = List<StoryAlbumDM>()
}
// Model class for the actual story album objects
class StoryAlbumDM: Object {
dynamic var id = 0
dynamic var type = ""
dynamic var isImage: Int = 0
dynamic var textData = ""
dynamic var imageData: NSData? = nil
dynamic var rowId: Int = 0
dynamic var position: Int = 0
dynamic var storyId: Int = 0
dynamic var isCoverImage: Int = 0
dynamic var imagePath = ""
}
This way, when you want to re-order the list, all you need to do is re-order them inside this array.
Like I said in the other question, one other way you can do it (Which is not as good, but also doesn't require an extra Realm object) is to add another property named orderedIndex, which simply contains a number indicating the numerical order of these objects. When you want to re-order them, it's simply a matter of re-setting these numbers.
Let me know if you need any more clarification!
The method below runs against a sqlite3 database. It's intended to fetch all of the primary keys for records matching each of the foreign keys in the array it's passed as a parameter (flds).
- (NSArray*) columnPrimaryKeysForFields:(NSArray*)flds
{
NSMutableArray* retval = [[NSMutableArray alloc] init];
NSString* query = #"SELECT ID FROM Pages WHERE FieldID = ? ORDER BY ID";
sqlite3_stmt* statement;
if (sqlite3_prepare_v2(_database, [query UTF8String], -1, &statement, nil) == SQLITE_OK)
{
for (NSNumber* fieldID in flds)
{
sqlite3_bind_int64(statement, 1, (int)[fieldID longValue]);
while (sqlite3_step(statement) == SQLITE_ROW)
{
[retval addObject:[NSNumber numberWithInteger:sqlite3_column_int(statement, 0)]];
}
}
sqlite3_finalize(statement);
}
else
{
NSLog(#"SQL PREPARE columnPrimaryKeysForFields failed");
}
return [NSArray arrayWithArray:retval];
}
In the database, there are multiple records containing each of the keys in flds. When the method executes it fetches all of the records containing first key in flds, but only the first record containing each of the subsequent keys in flds. I can't figure out why the first key in flds fetches the correct number of records but the subsequent keys do not.
Thanks in advance for your help!
You have to call sqlite3_reset after the last step call.
i am writing the code below manner.
NSDictionary* json = [NSJSONSerialization
JSONObjectWithData:responseData
options:kNilOptions error:&error];
NSLog(#"%#",json);
The printed dictionary is
(
{
Contents = (
{
Id = 2;
LastUpdated = "/Date(1338048712847+0000)/";
Title = "Webinar: HP & MS solutions for Mid-Market";
Url = "http://infra2apps.blob.core.windows.net/content/VMMM019-HP-MS_MidMarket.wmv";
},
{
Id = 1;
LastUpdated = "/Date(1338048712773+0000)/";
Title = "Webinar: Private Cloud with HP & MS";
Url = "http://infra2apps.blob.core.windows.net/content/VMPC012-HPMS_PrivateCloud.wmv";
}
);
Id = 1;
ImageUrl = "http://infra2apps.blob.core.windows.net/eventapp/black-microsoft-logo.jpg";
Name = "Unified Communications & Collaborations";
Sessions = (
{
Description = "Microsoft Lync delivers Unified Communication to help People connect in new ways, anytime, anywhere. Learn how HP and Microsoft are helping customers transform their business infrastrucutre and gain greater productivity by making every communication an interaction that is more collaborative and engaging.";
EndDate = "/Date(1275822000000+0000)/";
FriendlyName = TB3257;
Id = 1;
Location = "Building N-4105";
Speakers = (
{
Company = Microsoft;
Email = "johndoe#microsoft.com";
Name = "John Doe";
Title = "Group Manager";
}
);
StartDate = "/Date(1275818400000+0000)/";
Title = "Connecting People in New Ways with Microsoft Lync";
},
{
Description = "Microsoft Lync delivers Unified Communication to help People connect in new ways, anytime, anywhere. Learn how HP and Microsoft are helping customers transform their business infrastrucutre and gain greater productivity by making every communication an interaction that is more collaborative and engaging.";
EndDate = "/Date(1275825600000+0000)/";
FriendlyName = TB3258;
Id = 2;
Location = "Building N-4105";
Speakers = (
{
Company = HP;
Email = "janedoe#hp.com";
Name = "Jane Doe";
Title = "Vice President";
},
{
Company = Microsoft;
Email = "johndoe#microsoft.com";
Name = "John Doe";
Title = "Group Manager";
}
);
StartDate = "/Date(1275822000000+0000)/";
Title = "Connecting People in New Ways with Microsoft Lync - Part 2";
}
);
},
....etc
And then store the content values into another dictionary after that i store into an array.
the below code is to store the array id
NSDictionary *boothmenucontents = [json valueForKey: #"Contents"];
NSMutableArray *dictResponseboothmenucontentsArray = [[NSMutableArray alloc] initWithObjects: boothmenucontents,nil];
for(int i = 0; i<[dictResponseboothmenucontentsArray count]; i++)
{
NSMutableArray *IdArrayboothmenucontentes=[[dictResponseboothmenucontentsArray objectAtIndex:i] valueForKey:#"Id"];
NSLog(#"id array is %#",IdArrayboothmenucontentes);
for(int k=0;k<[IdArrayboothmenucontentes count];k++)
{
NSString * strcontentId= [NSString stringWithFormat:#"%#",[IdArrayboothmenucontentes objectAtIndex:k]];
NSLog(#"strcontentId%#",strcontentId);
label.text=strcontentId;
[boothmenuidarrayvalues addObject:strcontentId];
NSLog(#"%#",boothmenuidarrayvalues);
}
}
finally i print the boothmenuidarrayvalues
it print like this
"(\n 2,\n 1\n)",
"(\n 4,\n 3\n)",
"(\n 6,\n 5\n)",
"(\n 8,\n 7\n)",
"(\n 10,\n 9\n)",
"(\n 12,\n 11\n)"
but i want to print content id only once but it print in a row in two times.
May be i follow a wrong method please tell me how to give own root for that response.
Please help me.......
Perhaps It will help you.
NSMutableArray *contenstsArray = [contentsDictionary ValueForKey:#"Contents"]; //Suppose you already brought all the json data into contentsDictionary
NSMutableArray *idArray = [[NSMutableArray alloc] init];
for(NSMutableDictionary *idDic in contenstsArray) {
NSString *idString = [idDic valueForKey:#"Id"];
[idArray addObject:];
}
This line looks wrong:
NSMutableArray *IdArrayboothmenucontentes=[[dictResponseboothmenucontentsArray objectAtIndex:i] valueForKey:#"Id"];
I'm not sure what you are expecting it to do, but what it looks like it does is grab the ith object in the dictResponseboothmenucontentsArray, which is a dictionary and then gets the object in that dictionary with the key "Id", which is an number, so IdArrayboothmenucontentes now contains an NSNumber, not an array.
I manage to get Json for my server and parse in Xcode , I can then convert Json to a object and loaded my uitableview, the problems is my Json have 7 objects ..
you can see the full Json here
2012-05-05 10:45:02.727 passingdata[63856:fb03] array : {
posts = {
Friday = (
{
GymClass = {
"CLASS-TYPE2" = "";
"CLASS_LEVEL" = "Intro/General";
"CLASS_TYPE" = "Muay Thai";
"DAY_OF_WEEK" = Friday;
TIME = "13:00 - 14:30";
};
}
);
Monday = (
{
GymClass = {
"CLASS-TYPE2" = "Fighters Training";
"CLASS_LEVEL" = "Fighters/Advanced/Intermediate";
"CLASS_TYPE" = "Muay Thai ";
"DAY_OF_WEEK" = Monday;
TIME = "09:30 - 11:00";
};
}, ......
with this code I can get friday's "Friday" and display the GymClass info "GymClass" on my table
- (void)fetchedData:(NSData *)responseData { //parse out the json data
searchResults2 = [NSMutableArray arrayWithCapacity:10];
NSError* error;
NSDictionary* dictionary = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
NSLog(#"array : %#",dictionary);
NSArray *array = [[dictionary objectForKey:#"posts"] objectForKey:#"Friday"]; // retrieve that Day Gym Classes
if (array == nil) {
NSLog(#"Expected 'posts' array");
return;
}
for (NSDictionary *resultDict in array)
{
SearchResult *searchResult3;
searchResult3 = [self parseTrack:resultDict];
if (searchResult3 != nil) {
[searchResults2 addObject:searchResult3];
}
}
[self.tableView reloadData];
}
- (SearchResult *)parseTrack:(NSDictionary *)dictionary
{
SearchResult *searchResult1 = [[SearchResult alloc] init];
searchResult1.classType= [[dictionary objectForKey:#"GymClass"] objectForKey:#"CLASS_TYPE"];
searchResult1.classLevel= [[dictionary objectForKey:#"GymClass"] objectForKey:#"CLASS_LEVEL"];
NSLog(#"parse track = %#", searchResult1);
return searchResult1;
}
I can get the elements for one day but how do I get the Elements for every day (Mon,Tue...Sun)so i can display on my table by sections?
thanks for your help..
Well in your code, you already are doing that:
NSDictionary* dictionary = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
NSLog(#"array : %#",dictionary);
NSArray *array = [[dictionary objectForKey:#"posts"] objectForKey:#"Friday"]; // retrieve that Day Gym Classes
Wen can start from there to retrieve only the object posts:
NSDictionary* dictionary = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
NSDictionary *posts = [dictionary objectForKey:#"posts"];
//Iterate over posts
for (NSArray *aDay in posts){
//Do something
NSLog(#"Array: %#", aDay);
}
Here, i am using Fast Enumeration to iterate over the dictionary, you should check this here.
Hey guys im using the method above like:
string = [array componentsJoinedByString:#"\n"];
this prints out each obj in my array, but what it prints out is:
{
Selected = 0;
name = "boots";
number = 69;
}
{
Selected = 0;
name = house;
number = 1001;
}
}
Selected = 0;
name = shirt;
number = 1234;
}
{
Selected = 0;
name = Brewski;
number = 4567;
}
and i just want it to print out:
Brewski
Boots...
etc..
The objects in your array seem to be dictionaries. You should do this instead.
[[array valueForKey:#"name"] componentsJoinedByString:#"\n"]