Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I am confused with sorting NsArray as am very new in iOS development, I have a custom array, I want to sort my NsArray which has the value as below as group by callType and numberId:
{
callID = 1;
callType = 4;
dateTime = "2013-10-11 14:42:10 +0000";
durationOfCall = "00:00:27";
numberCalled = 91xxxxxxxxx;
numberId = 8;
},
{
callID = 1;
callType = 4;
dateTime = "2013-10-11 14:24:19 +0000";
durationOfCall = "00:00:15";
numberCalled = 91xxxxxxxxx;
numberId = 9;
},
{
callID = 1;
callType = 4;
dateTime = "2013-10-11 13:59:18 +0000";
durationOfCall = "00:00:11";
numberCalled = 91xxxxxxxxx;
numberId = 8;
},
{
callID = 1;
callType = 4;
dateTime = "2013-10-11 13:57:55 +0000";
durationOfCall = "00:00:09";
numberCalled = 91xxxxxxxxx;
numberId = 8;
},
{
callID = 1;
callType = 4;
dateTime = "2013-10-11 13:56:02 +0000";
durationOfCall = "00:00:12";
numberCalled = 91xxxxxxxxx;
numberId = 8;
},
{
callID = 1;
callType = 4;
dateTime = "2013-10-11 13:55:41 +0000";
durationOfCall = "00:00:00";
numberCalled = 91xxxxxxxxx;
numberId = 8;
}
)
and the result should be something like where i get the count in each group
{
count = 4 // number of
callID = 1;
callType = 4;
dateTime = "2013-10-11 14:42:10 +0000";
durationOfCall = "00:00:27";
numberCalled = 91xxxxxxxxx;
numberId = 8;
},
{
count = 1 // number of
callID = 1;
callType = 4;
dateTime = "2013-10-11 14:24:19 +0000";
durationOfCall = "00:00:27";
numberCalled = 91xxxxxxxxx;
numberId = 9;
}
}
Here is my custom class for above
#import <Foundation/Foundation.h>
#interface RecentCallsModel : NSObject
#property (nonatomic, retain) NSNumber *callID; // Integer 32
#property (nonatomic, retain) NSNumber *callType; // Integer32
#property (nonatomic, retain) NSString *numberId; // Either phone number or the contact id
#property (nonatomic, retain) NSDate *dateTime; //Date and time
#property (nonatomic, retain) NSString *durationOfCall;
#property (nonatomic, retain) NSString *numberCalled;
#end
it will work......
NSArray *sortedArray;
sortedArray = [array sortedArrayUsingComparator:^NSComparisonResult(id a, id b)
{
NSNumber *firstCallType = [(RecentCallsModel*)a CallType];
NSNumber *secondCallType = [(RecentCallsModel*)b CallType];
NSNumber *firstNumberID = [(RecentCallsModel*)a NumberID];
NSNumber *second NumberID = [(RecentCallsModel*)b NumberID];
if([firstCallType compare:secondCallType]==NSOrderedSame)
{
if([firstNumberID compare:secondNumberID]==NSOrderedSame)
{
//count logic
}
else
return [firstNumberID compare:secondNumberID];
}
else
return [firstCallType compare:secondCallType];
}];
Related
I have an array of NSDictionary.NSDictionary has a key named as multiple_image key that contain string separated by ,.
I want set of array that contain 123.png for multiple_images key.
Can some one show me how to do this using NSPredicate or without predicate.
//Array
{
Image = "<UIImage: 0xf72df30>";
active = yes;
"admin_id" = 169;
"category_id" = 32;
"chef_id" = 175;
descr = "Cool tea to cool down the mind.";
id = 110;
"multiple_images" = "Jellyfish.jpg,345.png";
name = "Southern Sweet Ice Tea";
price = 160;
rating = 3;
selected = 0;
"subcat_id" = 23;
"tag_id" = 45;
"tax_id" = 10;
"tax_value" = "12.00";
},
{
Image = "<UIImage: 0xf72ebd0>";
active = yes;
"admin_id" = 169;
"category_id" = 31;
"chef_id" = 175;
descr = "Ingredients are almonds or cashews. No hydrogenated stuff, no extra weirdo ingredients";
id = 107;
"multiple_images" = "Jellyfish.jpg,123.png";
name = "Butter Chicken";
price = 300;
rating = 3;
selected = 0;
"subcat_id" = 24;
"tag_id" = 43;
"tax_id" = 9;
"tax_value" = "0.00";
},
{
Image = "<UIImage: 0xf72f870>";
active = yes;
"admin_id" = 169;
"category_id" = 31;
"chef_id" = 173;
descr = "Raw vegetables including carrots, cucumbers.";
id = 100;
"multiple_images" = "Jellyfish.jpg,shake.png,";
name = Salads;
price = 50;
rating = 3;
selected = 0;
"subcat_id" = 22;
"tag_id" = 44;
"tax_id" = 9;
"tax_value" = "0.00";
}
Using predicates,
[array filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:#"multiple_images CONTAINS '123'"]];
Using predicates, but with blocks
NSArray *filtered = [test filteredArrayUsingPredicate:[NSPredicate predicateWithBlock:
^BOOL(NSDictionary *evaluatedObject, NSDictionary * bindings) {
NSString *key = #"123";
return ([evaluatedObject[#"multiple_images"] rangeOfString:key].location != NSNotFound);
}]];
Try
NSDictionary *item = mainArray[0];
NSString *imagesString = item[#"multiple_images"];
NSArray *images = [imagesString componentsSeparatedByString:#","];
Now you can use the images
Try this code
for (int i=0; i<[mainArray count]; i++) {
NSDictionary *item = [mainArray objectAtIndex:i];
NSString *imagesString = item[#"multiple_images"];
NSArray *images = [imagesString componentsSeparatedByString:#","];
for (int j=0;j<[images count]; j++) {
if ([[images objectAtIndex:j] isEqualToString:#"123.png"]) {
///Your Required code;
}
}
}
So you want to save the dictionary that has 123.png.
maybe you can try something like this:
NSMutableArray *arr = [NSMutableArray new];// your array of objects(dictionaries)
__block NSMutableArray *images123 = [NSMutableArray new];
[arr enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
NSMutableDictionary *dictionary = (NSMutableDictionary *)obj;
if([[dictionary allKeys]containsObject:#"multiple_images"]){
NSString *imageList = (NSString *)[dictionary objectForKey:#"multiple_images"];
NSArray *arrayImages = [imageList componentsSeparatedByString:#","];
if([arrayImages containsObject:#"123.png"]){
[images123 addObject:dictionary];
}
}
}];
Here I want to filter dictionary in the array which contains the "cate = subcat"
could anybody help me please
menuArr :(
{
Cate = subcat;
Description = "Grilled Chicken";
Id = 2;
Image = "http://asaraa.com/our_development/restaurant/admin/logo_image/large/28322grilled_chicken.jpg";
Name = "Grilled Chicken";
Price = 0;
Qty = "";
Title = "grilled chicken";
},
{
Cate = product;
Description = gravey;
Id = 12;
Image = "http://asaraa.com/our_development/restaurant/admin/logo_image/large/27166mutton.jpg";
Name = gravey;
Price = 50;
Qty = 1;
Title = gravey;
},
{
Cate = product;
Description = "Chicken Korma";
Id = 15;
Image = "http://asaraa.com/our_development/restaurant/admin/logo_image/large/77845Indian_chicken_recipes.jpg";
Name = "Chicken Korma";
Price = 99;
Qty = 1;
Title = "Chicken Korma";
},
{
Cate = subcat;
Description = "Chicken Sandwiches";
Id = 16;
Image = "http://asaraa.com/our_development/restaurant/admin/logo_image/large/67831chicken-sandwich-melt-0204_300.jpg";
Name = "Chicken Sandwiches";
Price = 0;
Qty = "";
Title = "Chicken Sandwiches";
}
)
NSString *searchString = #"subcat"
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"Cate = %#",searchString];
NSArray *array = [yourArray filteredArrayUsingPredicate:predicate];
if (array.count > 0)
{
// here goes your code
}
Using Linq to ObjectiveC you can filter it as follows:
NSArray* itemsInCategory = [menuArr where:^BOOL(id dic) {
return [[dic objectForKey:#"Cate"] isEqualToString:#"subcat"];
}];
This finds all the dictionaries where Cate=subcat.
Use NSPredicate
NSArray *filtered = [yourArray filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:#"(Cate LIKE[CD] %#)", #"subcat"]];
I have a write a simple json representing the position of same places like:
{
lat = "41.653048";
long = "-0.880677";
name = LIMPIA;
},
In iphone programming, my app is able to show the position on the map. My question is about how replicate the same on multiple position. For example with a json like:
{
lat = "41.653048";
long = "-0.890677";
name = name1 ;
},
{
lat = "41.653048";
long = "-0.890677";
name = name2;
},
How i can able to know the number of itemes? I have to change the json adding anything else in representation?or i have to completelin change it?
You need to use a JSON array:
[
{
lat = "41.653048";
long = "-0.890677";
name = name1 ;
},
{
lat = "41.653048";
long = "-0.890677";
name = name2;
},
]
I'm not sure I understand your question but it seems like you want to know how to best include multiple points in one JSON object?
{
"locations":
[
{
lat = "41.653048";
long = "-0.890677";
name = name1 ;
},
{
lat = "41.653048";
long = "-0.890677";
name = name2;
}
]
}
Not sure if you mean to parse or write JSON from/to objects. I outline both.
#interface MyPointModel : NSObject
#property (nonatomic, strong) NSNumber *latitude;
#property (nonatomic, strong) NSNumber *longitude;
#property (nonatomic, strong) NSString *name;
#end
#implementation MyPointModel
#synthesize latitude, longitude, name;
#end
Parsing
(and where ever you do the parsing)
#implementation ParsingController
...
- (NSArray *)buildArrayOfMyPointModelWithString:(NSString *)json {
NSArray *array = [jsonParser.objectWithString:json error:NULL];
NSMutableArray *arrayOfMyPointModel = [[NSMutableArray alloc] init];
for (id jsonElement in array) {
MyPointModel *m = [[MyPointModel alloc] init];
m.latitude = [jsonElement valueForKey:#"lat"];
m.longitude = [jsonElement valueForKey:#"long"];
m.name = [jsonElement valueForKey:#"name"];
[arrayOfMyPointModel addObject:m];
}
return (NSArray *)arrayOfMyPointModel;
}
Writing
(a sample array of my point)
NSMutableArray *a = [[NSMutableArray alloc] init];
MyPointModel *m1 = [[MyPointModel alloc] init];
MyPointModel *m2 = [[MyPointModel alloc] init];
m1.latitude = [NSNumber numberWithDouble:0.1];
m1.longitude = [NSNumber numberWithDouble:0.01];
m1.name = #"M1";
m2.latitude = [NSNumber numberWithDouble:0.2];
m2.longitude = [NSNumber numberWithDouble:0.02];
m2.name = #"M2";
[a addObject:m1];
[a addObject:m2];
- (NSString *)buildJsonStringWithMyPointModelArray:(NSArray *)array {
SBJsonWriter *writer = [[SBJsonWriter alloc] init];
return [writer stringWithObject:array];
}
I have implemented the array of dictionary contents accessing methods but it is access only one content, please help on this
Here is my data file
<__NSArrayM 0x8b7a350>(
{
clkDate = "Wednesday, April 11, 2012";
resData = (
{
data = 10;
independentItem = 0;
module = 6;
newDate = "11-4-2012";
newTime = "13:31";
seqCounter = 101;
sequence = 10007;
session = 101;
timeframe = Breakfast;
timestamp = "2012-04-11 08:01:27 +0000";
title = "Glucose reading : Low";
type = L;
},
{
data = {
hours = 0;
minutes = 0;
which = "Walking:(null)";
};
independentItem = 1;
module = 13;
seqCounter = 101;
sequence = 10009;
session = 101;
timestamp = "2012-04-12 08:01:40 +0000";
title = "Low Cause: Increased Exercise";
}
);
seqCounter = 101;
},
{
clkDate = "Thursday, April 12, 2012";
resData = (
{
data = 200;
independentItem = 0;
module = 6;
newDate = "12-4-2012";
newTime = "13:31";
seqCounter = 102;
sequence = 10017;
session = 101;
timeframe = Breakfast;
timestamp = "2012-04-12 08:01:46 +0000";
title = "Glucose reading : High";
type = H;
},
{
data = {
hours = 0;
minutes = 0;
which = "Other Light:Kkkkk";
};
independentItem = 1;
module = 26;
seqCounter = 102;
sequence = 10022;
session = 101;
timestamp = "2012-04-11 18:30:00 +0000";
title = "High Cause: Decreased Exercise";
}
);
seqCounter = 102;
},
{
clkDate = "Thursday, April 12, 2012";
clkIndependentItem = 1;
resData = (
{
data = {
bathing = 1;
driving = 1;
grocery = 1;
meal = 1;
};
independentItem = 1;
module = 31;
seqCounter = 103;
sequence = 10035;
session = 101;
timestamp = "2012-04-12 08:02:32 +0000";
title = "High Cause: Decreased activity";
}
);
seqCounter = 103;
}
)
In above data file i need to access "independentItem = 1" related items
i tried source code is
for (int i = 0; i < [self.gluClkDetailArray count]; i++)
{
NSMutableDictionary *mDict = [self.gluClkDetailArray objectAtIndex:i];
{
NSMutableArray *mResData = [mDict objectForKey:#"resData"];
NSDate *mTimestamp = [[mResData objectAtIndex:0] objectForKey:#"timestamp"];
NSDateFormatter *mFormatter = [[NSDateFormatter alloc] init];
[mFormatter setDateStyle:NSDateFormatterFullStyle];
NSString *mClkDate = [mFormatter stringFromDate:mTimestamp];
[mDict setValue:mClkDate forKey:#"clkDate"];
NSString *mIndItem = [[mResData objectAtIndex:0] objectForKey:#"independentItem"];
if (mIndItem.intValue == 1)
{
[mDict setValue:mIndItem forKey:#"clkIndependentItem"];
[mIndpendentArray addObject:mDict];
}
[gluClkResultArray addObject:mDict];
}
when ever i put the mResData objectAtIndex:0 instead of i, app got crashed. i have saved array of dictionary values based on the sequence counter
Thanks in advance
Change
NSString *mIndItem = [[mResData objectAtIndex:0] objectForKey:#"independentItem"];
to that:
NSString *mIndItem = [[mResData objectAtIndex:1] objectForKey:#"independentItem"];
The independentItem is in the dictionary that in at index 1, not 0.
Hope it helps
EDIT:
The Code:
//stores dictionary of questions
- (void)requestFinished:(ASIHTTPRequest *)request
{
NSData *responseData = [request responseData];
NSString *json = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSDictionary *qs = [json objectFromJSONString];
self.questions = qs;
NSLog(#"%#", questions);
[json release];
[self setQuestions];
[load fadeOut:load.view withDuration:0.7 andWait:0];
UIBarButtonItem *anotherButton = [[UIBarButtonItem alloc] initWithTitle:#"Start" style:UIBarButtonItemStylePlain target:self action:#selector(start:)];
self.navigationItem.rightBarButtonItem = anotherButton;
}
I have the following items in an NSDictionary:
(
{
max = 120;
min = 30;
question = "Morning Bodyweight (Kg)";
questionId = 1;
questionNumber = 1;
sectionId = 1;
type = TextInput;
},
{
question = "Morning Urine Colour";
questionId = 2;
questionNumber = 2;
sectionId = 1;
type = ImagePicker;
},
{
max = 120;
min = 30;
question = "Evening Bodyweight (Kg)";
questionId = 3;
questionNumber = 3;
sectionId = 1;
type = TextInput;
},
{
question = "Evening Urine Colour";
questionId = 4;
questionNumber = 4;
sectionId = 1;
type = ImagePicker;
},
{
max = 90;
min = 40;
question = "Morning Heart Rate (BPM)";
questionId = 5;
questionNumber = 5;
sectionId = 1;
type = TextInput;
},
{
question = "Time of Month (TOM)";
questionId = 6;
questionNumber = 6;
sectionId = 1;
type = Option;
}
)
I want to remove the last element:
{
question = "Time of Month (TOM)";
questionId = 6;
questionNumber = 6;
sectionId = 1;
type = Option;
}
Is there a pop() equivalent for the NSDictionary? If not how is it possible to remove the last element?
There is no order to dictionaries so there is no 'last object'
However, this might solve your problem, though it might not always remove what you are thinking the 'last object' is:
[dictionaryName removeObjectForKey:[[dictionaryName allKeys] lastObject]];
This looks to be (or could be made to be) an array of dictionaries. If you have these dictionaries as the objects of an NSMutableArray, then you can use – removeLastObject. Otherwise, you're SOL since even NSMutableDictionary has no such method.
There is no last element in a dictionary, as elements in a dictionary are not ordered.
Can you somehow get the element by using the key value? NSDictionaries don't have an ordering, so there's no such thing as removing the "last" element.
I think that's an array of NSDictionaries you got yourself there. In which case it's very easy to do:
NSMutableArray *mArray = [NSMutableArray arrayWithArray:array]; // if not mutable
[mArray removeLastObject];