I have a uicollectionView which display items from dictionaries (contained in a main dictionary in a plist). I need to sort it with the key "order" which is inside my dictionaries. I can't figure how to do this. I try to compare keys without success using descriptors.
I take the values from nsmutablearrays to display them in the cell.
Here my code (the one thart working unsorted):
//To retreive the data from the plist
NSMutableDictionary *items = [[NSMutableDictionary alloc] initWithContentsOfFile: finalPath];
//initialize arrays
_order = [[NSMutableArray alloc]initWithCapacity:10];
_name = [[NSMutableArray alloc]initWithCapacity:10];
_role = [[NSMutableArray alloc]initWithCapacity:10];
_image = [[NSMutableArray alloc]initWithCapacity:10];
_description = [[NSMutableArray alloc]initWithCapacity:10];
_email = [[NSMutableArray alloc]initWithCapacity:10];
_googleplus = [[NSMutableArray alloc]initWithCapacity:10];
//load every NSDictionnary on the view
NSMutableDictionary *loadedItem = [[NSMutableDictionary alloc]initWithCapacity:1];
NSMutableDictionary *theMember = [[NSMutableDictionary alloc]initWithCapacity:10];
loadedItem = [items objectForKey:#"Team"];
for (int i = 0; i < loadedItem.count; i++) {
theMember = loadedItem.allValues[i];
NSString *memberOrder = [theMember objectForKey:#"order"];
[_order addObject:memberOrder];
NSLog(#"member order = %#", _order);
NSString *memberName = [theMember objectForKey:#"name"];
[_name addObject:memberName];
NSLog(#"member name = %#", _name);
NSString *memberRole = [theMember objectForKey:#"role"];
[_role addObject:memberRole];
NSLog(#"member role = %#", _role);
NSString *memberImage = [theMember objectForKey:#"image"];
[_image addObject:memberImage];
NSLog(#"member image = %#", _image);
NSString *memberDesc = [theMember objectForKey:#"description"];
[_description addObject:memberDesc];
NSLog(#"member description = %#", _description);
NSString *memberMail = [theMember objectForKey:#"email"];
[_email addObject:memberMail];
NSLog(#"member mail = %#", _email);
NSString *memberGoogleplus = [theMember objectForKey:#"googleplus"];
[_googleplus addObject:memberGoogleplus];
NSLog(#"member googleplus = %#", _googleplus);
}
[self.collectionView reloadData];
}
I dealt with this by changing my mai ndict into an array which is better to manipulate.
Related
I have an NSMutableArray that contains several NSMutableDictionary object, each dict has a NSString and an NSMutableArray in it.
My problem is that I need to find the correct dict based on a string match and when found insert an object into the NSMutableArray in the same dict where the string match was found, I can only make this work the first time when the array is empty because after that I am unable to match the correct string:
Here is what I have tried so far, I tried using contains object but that wont get me inside the dict inside the array so I am stuck
NSMutableArray *variantOptions = [[NSMutableArray alloc] init];
for (NSDictionary *variant in variantInfo) {
NSMutableDictionary *variantOption = [[NSMutableDictionary alloc] init];
NSMutableArray *variantOptionValues = [[NSMutableArray alloc] init];
NSString *name = variant[#"name"];
NSString *value = variant[#"value"];
if(variantOptions.count > 0) {
// Need to loop through the array until name isEquaToString variantOptionName and when true insert value into variantOptionValuesArray in that same dict and if not exists create a new dict and insert in array
} else {
[variantOptionValues addObject:value];
[variantOption setObject:name forKey:#"variantOptionName"];
[variantOption setObject:variantOptionValues forKey:#"variantOptionValues"];
}
[variantOptions addObject:variantOption];
}
for (NSDictionary *variant in variantInfo) {
NSString *name = variant[#"name"];
NSString *value = variant[#"value"];
BOOL found = false;
for (NSMutableDictionary *v in variantOptions) {
if (v[#"name"] isequalToString:name]) {
NSMutableArray *values = v[#"variantOptionValues"];
[values addObject:value];
found = true;
break;
}
}
if (!found) {
// name was not found
NSMutableDictionary *variantOption = [[NSMutableDictionary alloc] init];
NSMutableArray *variantOptionValues = [NSMutableArray alloc] init];
[variantOptionValues addObject:value];
[variantOption setObject:name forKey:#"variantOptionName"];
[variantOption setObject:variantOptionValues forKey:#"variantOptionValues"];
[variantOptions addObject:variantOption];
}
}
I am creating a table with multiple columns. In the left column I want to get the indicator name which is stored in a database and I have to check that the indicator id in database and in json (API) matches and then display the name in that column. I have tried some code
In view load method I take values from database and store it in an array
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
appDelegate = (AppDelegate *) [[UIApplication sharedApplication] delegate];
indicatorName = [[NSMutableArray alloc] init];
NSString *path = appDelegate.databasePath;
FMDatabase *db = [[FMDatabase alloc] initWithPath:path];
[db open];
NSString *sql = [NSString stringWithFormat:#"SELECT * FROM Topic AS t INNER JOIN TopicIndicators AS ti ON t.Id = ti.TopicId INNER JOIN Indicators AS i ON ti.IndicatorID = i.Id"];// WHERE t.Id = %ld", (long)self.Tid];
FMResultSet *fresult = [db executeQuery:sql];
while ([fresult next])
{
TopicModel *topicModel = [[TopicModel alloc]init];
topicModel.TId = [fresult intForColumn:#"Id"];
topicModel.TTopicType = [fresult stringForColumn:#"TopicType"];
topicModel.TCode = [fresult stringForColumn:#"Code"];
topicModel.TName = [fresult stringForColumn:#"Name"];
topicModel.IId = [fresult intForColumn:#"Id"];
topicModel.ICodeId = [fresult stringForColumn:#"CodeId"];
topicModel.IName = [fresult stringForColumn:#"Name"];
topicModel.INotes = [fresult stringForColumn:#"Notes"];
topicModel.TIId = [fresult intForColumn:#"Id"];
topicModel.TITopicId = [fresult intForColumn:#"TopicId"];
topicModel.TIIndicatorID = [fresult intForColumn:#"IndicatorId"];
[indicatorName addObject:topicModel];
}
[db close];
mainTableData = [[NSMutableArray alloc] init];
[self callPages];
self.title = NSLocalizedString(#"Compare By", nil);
XCMultiTableView *tableView = [[XCMultiTableView alloc] initWithFrame:CGRectInset(self.view.bounds, 5.0f, 5.0f)];
tableView.leftHeaderEnable = YES;
tableView.datasource = self;
[self.view addSubview:tableView];
}
In request finished method I am taking values from json and assigning the values in appropriate columns.
-(void) requestFinished: (ASIHTTPRequest *) request
{
NSString *theJSON = [request responseString];
SBJsonParser *parser = [[SBJsonParser alloc] init];
NSMutableArray *jsonDictionary = [parser objectWithString:theJSON error:nil];
headData = [[NSMutableArray alloc] init];
NSMutableArray *head = [[NSMutableArray alloc] init];
leftTableData = [[NSMutableArray alloc] init];
NSMutableArray *left = [[NSMutableArray alloc] init];
rightTableData = [[NSMutableArray alloc]init];
for (NSMutableArray *dictionary in jsonDictionary)
{
Model *model = [[Model alloc]init];
model.cid = [[dictionary valueForKey:#"cid"]intValue];
model.iid = [[dictionary valueForKey:#"iid"]intValue];
model.yr = [[dictionary valueForKey:#"yr"]intValue];
model.val = [dictionary valueForKey:#"val"];
[head addObject:[NSString stringWithFormat:#"%ld", model.yr]];
[left addObject:[NSString stringWithFormat:#"%ld", model.iid]];
[mainTableData addObject:model];
}
NSOrderedSet *orderedSet = [NSOrderedSet orderedSetWithArray:head];
headData = [[orderedSet array] mutableCopy];
NSOrderedSet *orderedSet1 = [NSOrderedSet orderedSetWithArray:left];
NSMutableArray *arrLeft = [[orderedSet1 array] mutableCopy];
//remove duplicate enteries from header array
[leftTableData addObject:arrLeft];
NSMutableArray *right = [[NSMutableArray alloc]init];
for (int i = 0; i < arrLeft.count; i++)
{
NSMutableArray *array = [[NSMutableArray alloc] init];
for (int j = 0; j < headData.count; j++)
{
/* NSPredicate *predicate = [NSPredicate predicateWithFormat:#"SELF.iid == %ld", [[arrLeft objectAtIndex:i] intValue]];
NSArray *filteredArray = [mainTableData filteredArrayUsingPredicate:predicate];*/
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"SELF.iid == %ld AND SELF.yr == %ld", [[arrLeft objectAtIndex:i] intValue], [[headData objectAtIndex:j] intValue]];
NSArray *filteredArray = [mainTableData filteredArrayUsingPredicate:predicate];
NSMutableArray *newArray = [[NSMutableArray alloc] init];
TopicModel *topicModel = [[TopicModel alloc]init];
for (int k = 0; k < arrLeft.count; k++)
{
if (topicModel.IId == arrLeft[k])
{
[newArray addObject:[NSString stringWithFormat:#"%#",topicModel.IName]];
}
}
if([filteredArray count]>0)
{
Model *model = [filteredArray objectAtIndex:0];
[array addObject:model.val];
}
}
[right addObject:array];
}
[rightTableData addObject:right];
}
I am using FMDB, ASIHTTPRequest, SBJSON, XCMultisortTableView.
Please do help.
Well you are creating new TopicModel object which is empty! You need to use the one which you set in your viewDidLoad: method.
for (int k = 0; k < arrLeft.count; k++) {
if ([(TopicModel *)indicatorName[k] IId] == [arrLeft[k] integerValue]) {
[newArray addObject:[NSString stringWithFormat:#"%#",[(TopicModel *)indicatorName[k] IName]];
}
}
I have no problems to get the value of name in terms (name of my blog post category) out of the xmlrpc server response object ...
Server response:
responseArray: (
{ guid = "http://www.domain.com/wp/?p=12";
"post_id" = "123";
terms = (
{ name = "Uncategorized"; }
);
}
)
... with the following lines of Objective-C code:
NSMutableArray *responseArray = [[NSMutableArray alloc] init];
responseArray = [nodeSaveResponse object];
for(i = 0; i < responseArray.count; i++) {
NSString *postLink = [[responseArray objectAtIndex: i] valueForKey: #"guid"];
NSString *postId = [[responseArray objectAtIndex: i] valueForKey: #"post_id"];
NSMutableArray *catArray = [[NSMutableArray alloc] init];
catArray = [[responseArray objectAtIndex: i] valueForKey: #"terms"]];
NSArray *cat = [catArray valueForKey: #"name"];
NSString *myCatString = [cat objectAtIndex: 0];
}
But to send a new blog post fails because the following code to pack the category string is somehow wrong:
NSString *myCatString = #"MyCategory";
NSMutableDictionary *name = [[NSMutableDictionary dictionaryWithObjectsAndKeys: myCatString, #"name", nil];
NSMutableArray *catArray = [[NSMutableArray arrayWithObject: name];
NSMutableDictionary *values = [[NSMutableDictionary alloc] init];
[values setObject: title forKey: #"post_title"];
// and so on with other values - until here everything works well
[values setObject: catArray forKey: #"terms"]; // if this line is called, the request fails
NSArray *params = [NSArray arrayWithObjects: #"1", user, pass, values, nil];
[myRequest setMethod: #"wp.newPost" withParameter: params];
Any idea, where my fault is?
Cheers, Martin
When executing the below block. My friends_dict NSMutableDictionary value changes as friend changes. If I'm not wrong this is because the reference of the value in the dictionary is passed along to the friend. How can I pass the value instead of reference and prevent the dictionary from changing.
NSMutableArray *friendsArray = [[NSMutableArray alloc] initWithArray:[friends_dict valueForKey:selectedFriendId]];
for (NSObject *object in [response objectForKey:#"friend_nearby"]){
NSString *id = [NSString stringWithFormat:#"%#",[object valueForKey:#"id"]];
NSString *spotValue = [NSString stringWithFormat:#"%#",[object valueForKey:#"spot"]];
for(int i = 0; i < [friendsArray count]; i++){
FriendDataModel *friend = [[FriendDataModel alloc] init];
friend = [friendsArray objectAtIndex:i];
if ([friend.friendId isEqualToString:id] && ![friend.spot isEqualToString:spotValue] ) {
friend.spot = spotValue; //This is where the dictionary value changes
[friendsArray replaceObjectAtIndex:i withObject:friend];
spotChanged = YES;
}
}
}
Copy the array and pass in the copy.
NSArray *friendList = [friends_dict valueForKey:selectedFriendId];
NSMutableArray *friendsArray = [friendList mutableCopy];
I have an array of strings that I want to use as the filter for another array of dictionaries that is created from a plist. For example, if I had a plist of dictionaries that looked like so:
Key: Value:
car1 audi
car2 bmw
car3 bmw
car4 audi
car5 jaguar
and my array of strings was "audi, jaguar". How would I code it so that I can create a new array that would return "car1, car4, car5"? Hope this makes sense. Or better yet, how can I walk down this dictionary and filter it based on a value and then create a new array of dictionaries to use.
Code:
-(void)plotStationAnnotations {
desiredDepartments = [[NSMutableArray alloc] init];
BOOL tvfrSwitchStatus = [[NSUserDefaults standardUserDefaults] boolForKey:#"tvfrSwitchStatus"];
BOOL hfdSwitchStatus = [[NSUserDefaults standardUserDefaults] boolForKey:#"hfdSwitchStatus"];
if (tvfrSwitchStatus) {
NSString *tvfr = #"TVF&R";
[desiredDepartments addObject:tvfr];
}
if (hfdSwitchStatus) {
NSString *hfd = #"HFD";
[desiredDepartments addObject:hfd];
}
NSLog(#"Array 1 = %#", desiredDepartments);
NSString *path = [[NSBundle mainBundle] pathForResource:#"stationAnnotations" ofType:#"plist"];
NSMutableArray *anns = [[NSMutableArray alloc] initWithContentsOfFile:path];
NSMutableArray *newDictionaryArray = [NSMutableArray array];
for (NSDictionary *dictionary in anns) {
for (NSString *string in desiredDepartments) {
if ([dictionary allKeysForObject:string]) {
[newDictionaryArray addObject:dictionary];
break;
}
}
}
NSLog(#"Array = %#", keyMutableArray);
for (int i = 0; i < [keyMutableArray count]; i++) {
float realLatitude = [[[keyMutableArray objectAtIndex:i] objectForKey:#"latitude"] floatValue];
float realLongitude = [[[keyMutableArray objectAtIndex:i] objectForKey:#"longitude"] floatValue];
StationAnnotations *myAnnotation = [[StationAnnotations alloc] init];
CLLocationCoordinate2D theCoordinate;
theCoordinate.latitude = realLatitude;
theCoordinate.longitude = realLongitude;
myAnnotation.coordinate = theCoordinate;
myAnnotation.title = [[keyMutableArray objectAtIndex:i] objectForKey:#"station"];
myAnnotation.subtitle = [[keyMutableArray objectAtIndex:i] objectForKey:#"department"];
[mapView addAnnotation:myAnnotation];
}
}
May be something like
NSArray *array1;
if([array1 containsObject : someValue])
can help. someValue can be your values you want to check if they exist in array1.
You can do something like this to filter by keys:
NSArray *keysToLookFor = [NSArray arrayWithObjects:#"car1", #"car4", #"car5", nil];
NSArray *foundObjects = [dictionary objectsForKeys:keysToLookFor notFoundMarker:nil];
Or something like this to filter by values:
NSString *valueToLookFor = #"Audi";
NSArray *keyArray = [dictionary allKeysForObject:valueToLookFor];
// To filter by multiple values
NSArray *valuesToFilterBy = [NSArray arrayWithObjects:#"Bmw", #"Audi", nil];
NSMutableArray *keyMutableArray = [NSMutableArray array];
for (NSString *string in valuesToFilterBy) {
[keyMutableArray addObjectsFromArray:[dictionary allKeysForObject:string]];
}
Updated answer for dictionaries in arrays:
NSArray *dictionaryArray; // The array of dictionaries that you have
NSMutableArray *newDictionaryArray = [NSMutableArray array];
NSArray *valuesToFilterBy = [NSArray arrayWithObjects:#"Bmw", #"Audi", nil];
for (NSDictionary *dictionary in dictionaryArray) {
for (NSString *string in valuesToFilterBy) {
if ([dictionary allKeysForObject:string]) {
[newDictionaryArray addObject:dictionary];
break;
}
}
}