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];
}
Related
I have a NSObject class which's name is test.
class test has 3 property. Name, age, id;
I have 3 Objects in test class. s, b, c.
I am putting all of the objects to the array with: NSArray *ary = [NSArray arrayWithObjects:#"a", #"b", #"c", nil];
I am trying to access to the data of property in that array. Which means I have to read, write the property of the object in array in the loop (for loop or while loop).
I found a lot of materials on the internet. The method that I was close to do was:
[[ary objectAtIndex:0] setName:#"example"];
This method was working with setters and getters. But it did give a horrible error. Is there any "WORKING" method to do it?
Thanks...
Let's imagine a Person class:
#interface Person : NSObject
#property (nonatomic, copy) NSString *name;
#property (nonatomic) NSInteger age;
#property (nonatomic) long long identifier;
+ (instancetype)personWithName:(NSString *)name age:(NSInteger)age identifier:(long long)identifier;
#end
#implementation Person
+ (instancetype)personWithName:(NSString *)name age:(NSInteger)age identifier:(long long)identifier {
Person *person = [[self alloc] init];
person.name = name;
person.age = age;
person.identifier = identifier;
return person;
}
#end
You can then create an array of people like so:
NSArray *people = #[[Person personWithName:#"Rob" age:32 identifier:2452323],
[Person personWithName:#"Rachel" age:29 identifier:84583435],
[Person personWithName:#"Charlie" age:4 identifier:389433]];
You can then extract an array of people's names like so:
NSArray *names = [people valueForKey:#"name"];
NSLog(#"%#", names);
That will generate:
2013-09-27 14:57:13.791 MyApp[33198:a0b] (
Rob,
Rachel,
Charlie
)
If you want to extract information about the second Person, that would be:
Person *person = people[1];
NSString *name = person.name;
NSInteger age = person.age;
long long identifier = person.identifier;
If you want to change the age of the third person, it would be:
Person *person = people[2];
person.age = 5;
Or, if you want to iterate through the array to extract the information, you can do that, too:
for (Person *person in people) {
NSString *name = person.name;
NSInteger age = person.age;
long long identifier = person.identifier;
// now do whatever you want with name, age, and identifier
}
Try this
STEP 1 : Cast it to the appropriate object type first
s *myS = (s *)[array objectAtIndex:0];
b *myB = (b *)[array objectAtIndex:1];
c *myC = (c *)[array objectAtIndex:2];
STEP 2 : Set / get whatever property you want to
myS.name = #"example";
I have a dictionary of dictionaries. This is the structure of my main dictionary:
The content of dictionary(
{
mondaysSales= {
totalSale = "1234.99";
},
tusdaySales= {
totalSale = "1234.99";
},
wednesdaySale={
totalSale = "1234.99";
},
thursdaySale{
totalSale = "1234.99";
},
fridaySale{
totalSale = "1234.99";
}
)
but I want to add each day with the day key to a array. For example:
this would be one of the entries of the array:
fridaySale{
totalSale = "1234.99";
}
Any of you how can accomplish this?, I'll really appreciate your help.
You can loop through the dictionary and add it to the array. Note that dictionaries are not sorted and you probably won't end up with a correct order for your weekdays
NSMutableArray *array = [#[] mutableCopy]
for (NSString* key in dictionary) {
id value = [dictionary objectForKey:key];
[array addObject:value];
}
Why not create a new object type and add that to the array?
StorageObject.h:
#interface StorageObject:NSObject
#property (nonatomic, retain) NSString *day;
#property (nonatomic, retain) NSString *saleType;
#property (nonatomic, retain) NSNumber *saleValue;
#end
StorageObject.m:
#implementation StorageObject
#synthesize
day = _day,
saleType = _saleType,
saleValue = _saleValue;
- (void)dealloc
{
[_day release];
[_saleType release];
[_saleValue release];
[super dealloc];
}
#end
Now just loop through your NSDictionary using:
for(NSString *key in [dictionary1 allKeys])
{
NSDictionary *innerDictionary = [dictionary1 objectForKey:key];
}
For every dictionary returned in that loop, instantiate your custom storage object and add it to the array.
I figure out solution:
NSMutableDictionary *tempDict=[[NSMutableDictionary alloc]init];
[tempDict setObject:[mainDic objectForKey:key] forKey:key];
[myArray addObject:tempDict];
Assuming you have a dictionary of dictionaries:
You can do
NSMutableArray *list = [#[] mutableCopy];
for (NSString *key in [mainDictionary allKeys]) {
NSDictionary *dict = #{
key : [mainDictionary objectForKey:key],
};
[list addObject:dict];
}
There is an easy way to do this just don't create an NSDictionary and instead create an NSArray, by doing the following
NSArray *Array = #[#{#"friday sale, totalSale" : #"1234.99"}]
Or if you want to have specifics gotten from anything else in it.
NSInteger value = 1;
NSArray *Array = #[#{ #"Friday sale, totalSale" : [NSString stringWithFormat:#"%ld", (long)value]}];
Then you get this value from simply saying,
NSString *somestring = Array["Friday sale, totalSale"];
I have a json string:
{"1":{"homeTeam":"Home01","awayTeam":"Away01","homeScore":0,"awayScore":0,"gameID":1},"2":{"homeTeam":"Home11","awayTeam":"Away11","homeScore":0,"awayScore":0,"gameID":2},"3":{"homeTeam":"Home21","awayTeam":"Away21","homeScore":0,"awayScore":0,"gameID":3}}
that I would like to turn into an Objective-C class:
#import <Foundation/Foundation.h>
#interface ScoreKeeperGame : NSObject {
}
#property (nonatomic, retain) NSString *homeTeam;
#property (nonatomic, retain) NSString *awayTeam;
#property (nonatomic, assign) int homeScore;
#property (nonatomic, assign) int awayScore;
#property (nonatomic, assign) int gameID;
- (id) init: (NSString *) homeTeam
awayTeam: (NSString *) awayTeam;
- (id) init: (NSDictionary *) game;
#end
I pass the json in by NSDictionary "game" (the json string represents a hashmap, so the first game is):
{"homeTeam":"Home01","awayTeam":"Away01","homeScore":0,"awayScore":0,"gameID":1}
When I try to use this class:
#import "ScoreKeeperGame.h"
#implementation ScoreKeeperGame
#synthesize homeTeam=_homeTeam, awayTeam = _awayTeam, homeScore = _homeScore, awayScore = _awayScore, gameID = _gameID;
- (id) init: (NSString *) homeTeam
awayTeam: (NSString *) awayTeam
{
self = [super init];
self.homeTeam = homeTeam;
self.awayTeam = awayTeam;
NSLog(#"away: %#", awayTeam);
return self;
}
- (id) init: (NSDictionary *) game
{
self = [super init];
if(self)
{
self.homeTeam = [game objectForKey:#"homeTeam"];
self.awayTeam = [game objectForKey:#"awayTeam"];
self.awayScore = (int) [game objectForKey:#"awayScore"];
self.gameID = [game objectForKey:#"gameID"];
NSLog(#"game awayScore: %d", self.awayScore);
NSLog(#"game gameID: %#", [NSNumber numberWithInt:self.gameID]);
}
return self;
}
#end
The awayScore and gameId are printed as large numbers (maybe pointers)?
I've tried
self.awayScore = [NSNumber numberWithInt: [game objectForKey:#"awayScore"]];
But that didn't seem to work either.
How do I get the value of the int from the game object?
po game produces:
{
awayScore = 0;
awayTeam = Away01;
gameID = 1;
homeScore = 0;
homeTeam = Home01;
}
Thanks!
You have to pull it out as an NSNumber first.
NSNumber *myNum = [game objectForKey:#"awayScore"];
self.awayScore = [myNum intValue];
Doh!
you can try this if you want to get integer value from your JSON response
self.awayScore = [NSNumber numberWithInt: [[game objectForKey:#"awayScore"] intValue]];
as your response would be in nsstring.
iOs 6.0, now it's simply [game[#"awayScore"] intValue]
So in my model I have the following code... I am successfully able to return each individual value. I want to know how am I able to return the entire speakerTable []... Maybe some advice. Thanks!
typedef struct {
NSUInteger speakerID;
NSString * speakerName;
NSString * speakerPosition;
NSString * speakerCompany;
} SpeakerEntry;
static const SpeakerEntry speakerTable [] =
{
{0, #"name", #"position", #"company"},
{1, #"name", #"position", #"company"},
{-1, nil, nil, nil}
};
This works correctly...
-(NSString *) stringSpeakerCompanyForId:(NSUInteger) identifier{
NSString * returnString = nil;
if ([self helpCount] > identifier) {
returnString = speakerTable[identifier].speakerCompany;
}
return returnString;
}
This does not work at all..
-(id) getSpeaker{
//if ([speakerTable[0].speakerName isKindOfClass:[NSString class]])
// NSLog(#"YES");
NSArray * myArray3 = [NSArray arrayWithArray:speakerTable];
return myArray3;
}
arrayWithArray expects an NSArray, not a C array.
The first one works because you are using it like a C array.
Alternatively - don't use a struct, use an object instead:
Create a class called Speaker.
In Speaker.h
#interface Speaker : NSObject {}
#property (nonatomic, assign) NSUinteger id;
#property (nonatomic, copy) NSString name;
#property (nonatomic, copy) NSString position;
#property (nonatomic, copy) NSString company;
- (void)initWithId:(NSUInteger)anId name:(NSString *)aName position:(NSString *)aPosition company:(NSString *)aCompany;
#end
in Speaker.m
#import "Speaker.h"
#implementation Speaker
#synthesize id, name, position, company;
- (void)initWithId:(NSUInteger)anId name:(NSString *)aName position:(NSString *)aPosition company:(NSString *)aCompany {
if (!([super init])) {
return nil;
}
id = anId;
NSString name = [[NSString alloc] initWithString:aName];
NSString position = [[NSString alloc] initWithString:aPosition];
NSString company = [[NSString alloc] initWithString:aCompany];
return self;
}
- (void)dealloc {
[name release];
[position release];
[company release];
[super dealloc];
}
#end
And now in your calling code you can create an immutable array of speakers with:
Speaker *speaker0 = [[Speaker alloc] initWithId:0 name:#"name0" position:#"position0" company:#"company0"];
Speaker *speaker1 = [[Speaker alloc] initWithId:1 name:#"name1" position:#"position1" company:#"company1"];
Speaker *speakerNull = [[Speaker alloc] initWithId:-1 name:nil position:nil company:nil];
NSArray *speakerArray [[NSArray arrayWithObjects: speaker0, speaker1, speakerNull] retain]
[speaker0 release];
[speaker1 release];
[speakerNull release];
note: this is typed straight in, so feel free to mention/correct typos or errors
The method arrayWithArray takes in an NSArray as an argument, not a C array.
I want to create a nested array or multidimensional array.
In my data is,
FirstName class year dept lastName
Bob MBA 2000 Comp Smith
Jack MS 2001 Comp McDonald
NSMutableArray *section = [[NSMutableArray alloc] init];
I want to put my data into the section Array.
Eg:
section[0] = [FirstName,LastName];
section[1] = [class, year, dept];
So how can i put the values into array like that.
Please help me out.
Thanks
I would recommend creating a custom data storage class. You could call it PDPerson.h You'll also need the .m file. For each property, do something like this:
In the .h: Declare each of your properties like so:
#interface PDPerson : NSObject{
}
#property(nonatomic, retain) NSString *firstName;
#property(nonatomic, retain) NSString *lastName;
#property(nonatomic, retain) NSString *class;//May want to consider renaming
#property(nonatomic, retain) NSString *year;
#property(nonatomic, retain) NSString *dept;
#end
Then in the .m:
#implementation
#synthesize firstName, lastName;
#synthesize class, year dept;
-(void)dealloc{
[firstName release];
[lastName release];
[class release];
[year release];
[dept release];
}
Each time you want to create a new "Person" in your array, do this:
PDPerson *person = [[PDPerson alloc]init];
You can then easily set the properties of the object like so:
person.firstName = #"John";
person.lastName = #"Smith";
person.class = #"Math";
person.year = #"1995";
person.dept = #"Sciences";
And retrieve them:
firstNameLabel.text = person.firstName;
The nice thing about these objects is that all you have to do now is add the person object to your array:
NSMutableArray *personArray = [[NSMutableArray alloc] init];
[personArray addObject:person];
NSArray *section1 = [NSArray arrayWithObjects: #"1,1", #"1,2", #"1,3", nil];
NSArray *section2 = [NSArray arrayWithObjects: #"2,1", #"2,2", #"2,3", nil];
NSArray *section3 = [NSArray arrayWithObjects: #"3,1", #"3,2", #"3,3", nil];
NSArray *sections = [NSArray arrayWithObjects: section1, section2, section3, nil];
int sectionIndex = 1;
int columnIndex = 0;
id value = [[sections objectAtIndex:sectionIndex] objectAtIndex:columnIndex];
NSLog(#"%#", value); //prints "2,1"
Be warned, this isn't a flexible way of storing data. Consider using CoreData or creating your own classes to represent the data.
You can just nest multiple NSArray instances within an NSArray.
For example:
NSMutableArray* sections = [[NSMutableArray alloc] init];
for (int i = 0; i < numberOfSections; i++)
{
NSMutableArray* personsInSection = [[NSMutableArray alloc] init];
[sections insertObject:personsInSection atIndex:i];
for (int x = 0; x < numberOfPersons; x++)
{
Person* person = [[Person alloc] init];
[personsInSection insertObject:person atIndex:x];
}
}
This may seem like overkill when coming from languages such as C++ or Java, where multidimensional arrays can be created simply by using multiple sequare brackets. But this is way things are done with Objective-C and Cocoa.