Objectivc-c - Making objects of values in pList - objective-c

I have a pList looking like this when i log it:
{
Hans = {
Highscore = 0;
Name = Hans;
};
},
{
joe = {
Highscore = 0;
Name = joe;
};
},
{
Iben = {
Highscore = 0;
Name = Iben;
};
},
{
Erik = {
Highscore = 0;
Name = Erik;
};
}
I would really like to make these values in my pList into objects of Players when ViewDidLoad is called. Im not sure how to do so thought. Can somebody maybe help?

Load the plist into an array (appears you already have this but still I added this step)
NSString *path = [[NSBundle mainBundle] pathForResource:#"PlayerData" //Filename
ofType:#"plist"];
NSArray *loadedArray = [[NSArray alloc] initWithContentsOfFile:path];
Create an empty mutable array to store your player instances:
NSMutableArray *playersArray = [[NSMutableArray alloc] init];
Loop through your loaded array, creating Player instances and adding them to your mutable array
for (NSDictionary *dictionary in loadedArray) {
Player *player = [[Player alloc] init];
player.name = dictionary[#"Name"];
player.highscore = dictionary[#"Highscore"];
[playersArray addObject:player];
}
Note: Ideally you want a initialiser method in your player, like this:
- (instancetype)initWithName:(NSString *)name highscore:(NSNumber *)highscore;

Related

How to create a new ITLibMediaItem object?

I'm trying build an app that will work with iTunes. So, I imported the framework into my project and created a small class, just for learning purposes as follows:
-(NSMutableArray *)processMediaItems:(NSArray *)mediaItems {
NSMutableArray *titles = [NSMutableArray new];
if (mediaItems) {
for (ITLibMediaItem *item in mediaItems) {
[titles addObject:[item.title]];
}
}
return titles;
}
Then I decided to create a unit test for it, and did the following:
- (void)testExample {
ITLibMediaItem *mediaItem = [[ITLibMediaItem alloc] init];
//mediaItem.title = #"I Still Haven't Found What I'm Looking For";
NSMutableArray *mediaItems = [NSMutableArray new];
[mediaItems addObject:mediaItem];
MyClass *mc = [MyClass new];
NSMutableArray *titles = [mc processMediaItems:mediaItems];
}
The problem is that the property title is readonly.
So my question is, how do I create a new ITLibMediaItem object with a title? I tried to read the API (ITLibMediaItem) but didn't found a initialization that could help...
I find it. Properties in ITLibMediaItem are filled using setValuesForKeysWithDictionary:
NSMutableDictionary *properties = [NSMutableDictionary dictionary];
[properties setObject:#"I Still Haven't Found What I'm Looking For" forKey:#"title"];
ITLibMediaItem *mediaItem = [[ITLibMediaItem alloc] init];
[mediaItem setValuesForKeysWithDictionary:properties];
NSMutableArray *mediaItems = [NSMutableArray new];
[mediaItems addObject:mediaItem];

How to store { "Abc" :"Xyz" } in NSDictionary in Objective C

How to store the given below into NSDictionary
{
"Test":"Example"
}
You can add value for key by using this
NSDictionary *dictionary=[NSDictionary dictionaryWithObjectsAndKeys:#"Test",#"Example", nil];
You can add value for key by using 'initWithObjects:(objects) forKeys:'
NSDictionary* dictionary = [[NSDictionary alloc] initWithObjects:#[#"Example",#"Example2"] forKeys:#[#"Test",#"Test2"]];
NSLog(#"%#",dictionary);
//{
// Test = Example;
// Test2 = Example2;
//}
Or you can use NSMutableDictionary :
NSMutableDictionary *mutableDictionary = [[NSMutableDictionary alloc] init];
[mutableDictionary setObject:#"Example" forKey:#"Test"];
[mutableDictionary setObject:#"Example2" forKey:#"Test2"];
NSLog(#"%#",mutableDictionary);
//{
// Test = Example;
// Test2 = Example2;
//}
Same output for these. Also you should take a look

Cocoa [[NSWorkspace sharedWorkspace] iconForFile:filePath caused memory leaks

I am creating a cocoa application where i need to find out the icon images of file/directory. I am using this for getting icon image form the given path.
NSImage *image = [[NSWorkspace sharedWorkspace] iconForFile:path];
This method is called recessively in whole application. The allocated memory of the application is increased as much i use my app. Using instruments when i look for the memory leaks, i find out that the above method is responsible for the 100% memory leaks.
How can i remove this memory leaks, or is their any other way why which i can get icon image and memory will not be a problem.
Please help me someone.
Thanks
Edited:
This is the method from which i am calling this method.
-(WEFile *)fileAtPath:(NSString *)filePath
{
WEFile *file = [[WEFile alloc] init];
file.fIconImage = [workSpace iconForFile:filePath];
file.Name = [fileManager displayNameAtPath:filePath];
file.type = [workSpace localizedDescriptionForType:[workSpace typeOfFile:filePath error:&error]];
NSDictionary *detailDict = [fileManager attributesOfItemAtPath:filePath error:&error];
file.modificationDate = [ Utility createDateFormat:[detailDict objectForKey:NSFileModificationDate]];
file.creationDate = [ Utility createDateFormat:[detailDict objectForKey:NSFileCreationDate]];
file.Size = [[detailDict objectForKey:NSFileSize] integerValue];
file.fPath = filePath;
NSDictionary *metaDict = [self metadataForFileAtPath:filePath];
file.addedDate = [ Utility createDateFormat:[metaDict objectForKey:#"kMDItemDateAdded"]];
file.lastOpenedDate = [ Utility createDateFormat:[metaDict objectForKey:#"kMDItemLastUsedDate"]];
return [file autorelease];
}
The method fileAtPath is called recursively from another and the WEFile class objects are stored in a array. and display in a tableview.
EDIT 2: Here is the code from where i call fileAtPath method. And this method directoryAtPath is called when table selection passing path of directory as a parameter.
-(WEDirectory *)directoryAtPath:(NSString *)dirPath
{
WEDirectory *dir = [[[WEDirectory alloc] init] autorelease];
NSArray *childArray = [self getContentsWithinDirectory:dirPath];
if (childArray && [childArray count]>0)
{
for (int i = 0; i<[childArray count]; i++)
{
NSURL *fileURL = [childArray objectAtIndex:i];
NSString *filePath = [self getPathFromURL:fileURL];
filePath = [filePath stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
BOOL isDir;
BOOL success = [fileManager fileExistsAtPath:filePath isDirectory:&isDir];
if (!success)
{
continue;
}
if(isDir)
{
WEDirectory *childDir = [[WEDirectory alloc] init] ;
childDir.dIconImage = [workSpace iconForFile:filePath];
childDir.Name = [fileManager displayNameAtPath:filePath];
childDir.type = [workSpace localizedDescriptionForType:[workSpace typeOfFile:dirPath error:&error]];
NSDictionary *detailDict = [fileManager attributesOfItemAtPath:filePath error:&error];
childDir.modificationDate = [ Utility createDateFormat:[detailDict objectForKey:NSFileModificationDate]];
childDir.creationDate = [ Utility createDateFormat:[detailDict objectForKey:NSFileCreationDate]];
childDir.Size = [[detailDict objectForKey:NSFileSize]integerValue];
childDir.dPath = filePath;
[dir.childsArray addObject:childDir];
[childDir release];
}
else
{
WEFile *childFile = [self fileAtPath:filePath];
[dir.childsArray addObject:childFile];
}
}
}
return dir ;
}
This works without causing memory leaks in my code - checked it with Leaks/Allocations:
GAppSettings.h your WEFile-class
NSImage *gAppIcon;
#property (readwrite, retain) NSImage *gAppIcon;
*.m
#synthesize gAppIcon;
in ->init
gAppIcon = nil;
in -> dealloc
[ gAppIcon release];
I am also using for storing and restoring
->initWithCoder
self.gAppIcon = [ decoder decodeObjectForKey:#"gAppIcon"];
->encodeWithCoder
[ coder encodeObject: [ self gAppIcon] forKey: #"gAppIcon"];
and
- ( id ) copyWithZone: ( NSZone *)zone
{
return self;
}
The icon is loaded frequently in another class:
GAppSettings *appSettings = [ [ [GAppSettings alloc] init] autorelease];
...
NSImage *appIcon = [ [ NSWorkspace sharedWorkspace] iconForFile:completeAppPath];
[ appSettings setGAppIcon:appIcon];
...
return appSettings;
Then added to an array...

JSON data messed up in AFNetworking POST request

I am sending a request with AFNetworking for Objective-C. When I NSLog the parameters this is the object I am sending:
games = (
{
id = 50;
p = 8;
ts = 0;
tt = ();
tw = 0;
ys = 35150;
yt = {
156424496 = "37.416669";
156609008 = "56.661210";
....
252846816 = "7.075133";
252856944 = "61.329850";
};
yw = 0;
}, ...
This is what the server receives.
games = (
{id = 50;},
{p = 8;},
{ts = 0;},
{tw = 0;},
{ys = 35150;},
{
yt = {156424496 = "37.416669";};
},
{
yt = {156609008 = "56.661210";};
},
...
{
yt = {252846816 = "7.075133";};
},
{
yt = {252856944 = "61.329850";};
},
{yw = 0;},
...
It is as if it is taking each property of my object and creating a new object with it. The worse part is that it's taking the multiple objects that are in the array and putting all properties of all objects and turning them into separate object on the same depth of the array.
Here is the code I am using to send this off:
NSArray *games = [ResourceManager getAllGames];
NSMutableArray *gamesArray = [[NSMutableArray alloc] initWithCapacity:[games count]];
for(Game *g in games)
{
[gamesArray addObject:[g toDictionary]];
}
User *user = [ResourceManager getUser];
NSDictionary *params = [[NSDictionary alloc] initWithObjectsAndKeys:gamesArray, #"games", user.id, #"user_id", nil];
NSLog(#"PARAMS: %#", params); <- this is the first block of code above
[self postPath:API_SYNC_GAMES_URL parameters:params success:^(AFHTTPRequestOperation *operation, id JSON)
{
}
I have not been able to figure out why this would be happening, and I am all out of guesses. If someone could point me in the right direction it would be very appreciated.
UPDATE
If I post a single object rather than an array of the objects it arrives at the server successfully.
I was able to solve this issue by using an NSDictionary instead of an array. Each object I have has a unique key so I used that key for the NSDictionary like so:
NSMutableDictionary *gamesArray = [[NSMutableDictionary alloc]
initWithCapacity:[games count]];
for(Game *g in games)
{
[gamesArray setObject:[g toDictionary]
forKey:[NSString stringWithFormat:#"%#", g.id]];
}
That seems to have solved the issue.
Take a look at my answer here:
How can I POST an NSArray of NSDictionaries inside an NSDictionary without problems?
It solves all your problems.

NSDictionary to UITableView

I have a JSON request getting this:
bills = (
{
id = 1;
name = "Cursus Nibh Venenatis";
value = "875.24";
},
{
id = 2;
name = "Elit Fusce";
value = "254.02";
}
);
I'm creating a NSDictionary for it.
I'm using JSONKit and I wanna know how can I populate my UITableView with this values? Thanks for any help!
EDIT
NSLog(#"my dictionary = %#", resultsDictionary);
my dictionary = {
bills = (
{
id = 1;
name = "Cursus Nibh Venenatis";
value = "875.24";
},
{
id = 2;
name = "Elit Fusce";
value = "254.02";
}
);
}
It looks like your bills dictionary is composed of an array of smaller dictionaries. You'd access it like this;
get the top Dictionary bills.
access each dictionary inside (for loop, etc) and create an array
load table view data from previously created array
Edit*
NSDictionary *billsDictionary = [NSDictionary dictionaryWithDictionary:[resultsDictionary objectForKey:bills]];
NSMutableArray *dataSource = [[NSMutableArray alloc]init]; //make this an ivar and your tabelView's data source.
for(NSDictionary *dict in billsDictionary){
[dataSource addObject:dict];
}
[tableView reloadData];
//then in your tableView cell
cell.textLabel.text = [[NSString stringWithFormat:#"%#", [[dataSource objectAtIndex:indexPath.row]objectForKey:#"name"]]
//Repeat for whatever else you want to add to the cell (subtitle, image, etc.) Hope this helps.
It seems like In the result dictionary, you are having an Array. Where each object in your Array is a dictionary. Tryout the following code.
NSArray *billsArray = [resultsDictionary objectForKey:#"bills"];
give [[billsArray objectAtIndex:indexPath.row] objectForKey:#"name"] in your tableView datasource method tableView: cellForRowAtIndexPath: