NSMutableArray or NSArray structures - iphone

In NSMutableArray or NSArray how do you set up the row structure. All the examples I can find just deal with one dimensional integers or strings.
So how do you go about setting up an array row structure like:
Integer, String, Date

You would need to create an array of arrays, or an array of dictionaries, the second approach being better if you'd like to refer to the data by name rather than index:
NSMutableArray *rows = [[NSMutableArray alloc] init];
NSMutableDictionary *firstRow = [NSMutableDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithInt:12], #"fieldWithNumber",
[NSString stringWithFormat:#"A formatted string %ld", 34], #"fieldWithString",
[NSDate date], #"fieldWithDate",
nil];
[rows addObject:firstRow];
// etc.

You can make custom class and add collection of these objects in an array.
For example please assume that we have to do some rows about places then create a class PLACE.h
#interface PLACE : NSObject
{
NSString *title;
NSString *summary;
NSString *url;
NSString *latitude;
NSString *longitude;
}
#property (nonatomic, retain) NSString *title;
#property (nonatomic, retain) NSString *summary;
#property (nonatomic, retain) NSString *url;
#property (nonatomic, retain) NSString *latitude;
#property (nonatomic, retain) NSString *longitude;
#end
PLACE.m
#implementation PLACE
#synthesize title;
#synthesize summary;
#synthesize url;
#synthesize latitude;
#synthesize longitude;
- (void) dealloc
{
[title release];
[summary release];
[url release];
[latitude release];
[longitude release];
[super dealloc];
}
#end
Create instance of the class PLACE for each place and hold the objects in the array. I think that solves your problem.

An array is just a collection of objects.
Just create an object that has an integer, date and string and then add instances of those to the array.

Related

Save several ints to array and show total value in a label

What I like to do:
User enters 10 in UITextField and tap on UIButton.
UILabel shows 10 and UITextField goes blank.
User enters 5 in UITextField and tap on UIButton.
UILable shows 15 and UITextField goes blank again.
With following code I get the entered number saved and shown in the label but how can I tell the array to add and show me total and not just the very first number I entered?
h
#import <UIKit/UIKit.h>
#interface ViewController : UIViewController
#property (nonatomic, strong) IBOutlet UILabel *label;
#property (nonatomic, strong) IBOutlet UITextField *field;
#property (nonatomic, strong) NSString *dataFilePath;
#property (nonatomic, strong) NSString *docsDir;
#property (nonatomic, strong) NSArray *dirPaths;
#property (nonatomic, strong) NSFileManager *fileMgr;
#property (nonatomic, strong) NSMutableArray *array;
- (IBAction)saveNumber:(id)sender;
#end
m
#import "ViewController.h"
#interface ViewController ()
#end
#implementation ViewController
#synthesize label, field, dataFilePath, docsDir, fileMgr, dirPaths, array;
- (void)viewDidLoad
{
[super viewDidLoad];
fileMgr = [NSFileManager defaultManager];
dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
docsDir = [dirPaths objectAtIndex:0];
dataFilePath = [[NSString alloc]initWithString:[docsDir stringByAppendingPathComponent:#"data.archive"]];
if ([fileMgr fileExistsAtPath:dataFilePath])
{
array = [NSKeyedUnarchiver unarchiveObjectWithFile:dataFilePath];
self.label.text = [array objectAtIndex:0];
}
else
{
array = [[NSMutableArray alloc] init];
}
}
- (IBAction)saveNumber:(id)sender
{
[array addObject:self.field.text];
[NSKeyedArchiver archiveRootObject:array toFile:dataFilePath];
[field setText:#""];
[label setText:[array objectAtIndex:0]];
}
You need to iterate through all the values and add them to a running total. Have a look at this:-
- (IBAction)saveNumber:(id)sender
{
[array addObject:self.field.text];
[NSKeyedArchiver archiveRootObject:array toFile:dataFilePath];
[field setText:#""];
// Create an enumerator from the array to easily iterate
NSEnumerator *e = [array objectEnumerator];
// Create a running total and temp string
int total = 0;
NSString stringNumber;
// Enumerate through all elements of the array
while (stringNumber = [e nextObject]) {
// Add current number to the running total
total += [stringNumber intValue];
}
// Now set the label to the total of all numbers
[label setText:[NSString stringWithFormat:#"%d",total];
}
I've commented the code for readability.
Iterate over the array, get all values as numbers using [string intValue] and sum them up in another variable. Then add the calculated value to the label using a formatted string like [NSString stringWithFormat: #"%d"].

Leaky Custom Object for storing data from a plist

I have made a very simple custom object pictureData.
Here is the .h file
#import <Foundation/Foundation.h>
#interface pictureData : NSObject {
NSString *fileName;
NSString *photographer;
NSString *title;
NSString *license;
}
#property (nonatomic, retain) NSString *fileName;
#property (nonatomic, retain) NSString *photographer;
#property (nonatomic, retain) NSString *title;
#property (nonatomic, retain) NSString *license;
+(pictureData*)picDataWith:(NSDictionary*)dictionary;
#end
The .m file
#import "pictureData.h"
#implementation pictureData
#synthesize fileName;
#synthesize photographer;
#synthesize title;
#synthesize license;
+ (pictureData*)picDataWith:(NSDictionary *)dictionary {
pictureData *tmp = [[[pictureData alloc] init] autorelease];
tmp.fileName = [dictionary objectForKey:#"fileName"];
tmp.photographer = [dictionary objectForKey:#"photographer"];
tmp.title = [dictionary objectForKey:#"title"];
tmp.license = [dictionary objectForKey:#"license"];
return tmp;
}
-(void)dealloc {
[fileName release];
[photographer release];
[title release];
[license release];
}
#end
I then set up these objects in an array, like so:
NSString *path = [[NSBundle mainBundle] pathForResource:#"pictureLicenses" ofType:#"plist"];
NSArray *tmpDataSource = [NSArray arrayWithContentsOfFile:path];
NSMutableArray *tmp = [[NSMutableArray alloc] init];
self.dataSource = tmp;
[tmp release];
for (NSDictionary *dict in tmpDataSource) {
pictureData *pic = [pictureData picDataWith:dict];
NSLog(#"%#", pic.title);
[self.dataSource addObject:pic];
}
Everything works smashingly. I have a table view which loads the proper picture images, and information, no problem. Upon running Instruments for leaks, I see that my pictureData object is leaks with every allocation.
I would assume that with having my object autoreleased I would not have to worry about manually allocating and deallocating them.
Perhaps is my issue that I use autorelease, which the autoReleasePool keeps a retain count of +1 and then when I add a pictureData object to my array, that also retains it? Thank you all for your time!
edit: Don't forget to call super! Thank you Sam!
Change dealloc to:
-(void)dealloc {
[fileName release];
[photographer release];
[title release];
[license release];
[super dealloc];
}
(call [super dealloc])
In your function, change the return value to include autorelease, like
+ (pictureData*)picDataWith:(NSDictionary *)dictionary
{
...
...
return [tmp autorelease];
}
When you add pictureData object to dataSource, you increase the retain count, so you should autorelease it while returning.
Hope it helps.

Memory leak in a class with 3 NSMutableArrays. Why?

I'm getting a memory leak with instruments in a class that I've created. This is the class:
.h
#import <Foundation/Foundation.h>
#interface RDItem : NSObject {
}
#property int Id;
#property (nonatomic, retain) NSString *nombre;
#property (nonatomic, retain) NSString *thumbnail;
#property (nonatomic, retain) NSString *thumbnailPush;
#property int defaultColorId;
#property int idTema;
#property (nonatomic, retain) NSString *selectedFrame;
#property (nonatomic, retain) NSString *mergedFrame;
#property (nonatomic, retain) NSMutableArray *colors;
#property (nonatomic, retain) NSMutableArray *textures;
#property (nonatomic, retain) NSMutableArray *styles;
-(void)initialize;
#end
.m
#import "RDItem.h"
#implementation RDItem
#synthesize Id;
#synthesize nombre;
#synthesize thumbnail;
#synthesize thumbnailPush;
#synthesize defaultColorId;
#synthesize idTema;
#synthesize selectedFrame;
#synthesize mergedFrame;
#synthesize colors;
#synthesize textures;
#synthesize styles;
-(void)initialize
{
colors = [[NSMutableArray alloc] init];
textures = [[NSMutableArray alloc] init];
styles = [[NSMutableArray alloc] init];
}
-(void)dealloc
{
[colors release];
[textures release];
[styles release];
}
#end
This class have 3 NSMutableArray where I'll store data. In order to prepare and initialice this class, I've developed the method initialize where the 3 arrays are created. In dealloc are released.
The leaks tool detects a leak each time this class is used because the initialize method.
Which is the best way to initialize these arrays?
Thanks.
EDIT
Hi I've solved the leak with RDItem but now appears another lear in a very similar class:
.h
#import <Foundation/Foundation.h>
#interface RDTema : NSObject {
}
#property int Id;
#property (nonatomic, retain) NSString *idManifest;
#property (nonatomic, retain) NSString *idTema;
#property (nonatomic, retain) NSString *nombre;
#property (nonatomic, retain) NSString *thumbnail;
#property (nonatomic, retain) NSString *thumbnailPush;
#property (nonatomic, retain) NSMutableArray *items;
#property (nonatomic, retain) NSMutableArray *colors;
#property (nonatomic, retain) NSMutableArray *textures;
#property (nonatomic, retain) NSMutableArray *styles;
-(void)initialize;
#end
.m
#import "RDTema.h"
#implementation RDTema
#synthesize Id;
#synthesize idManifest;
#synthesize idTema;
#synthesize nombre;
#synthesize thumbnail;
#synthesize thumbnailPush;
#synthesize items;
#synthesize colors;
#synthesize textures;
#synthesize styles;
-(void)initialize
{
/*
self.items = [[NSMutableArray alloc] init];
self.colors = [[NSMutableArray alloc] init];
self.textures = [[NSMutableArray alloc] init];
self.styles = [[NSMutableArray alloc] init];
*/
self.items = [NSMutableArray array];
self.colors = [NSMutableArray array];
self.textures = [NSMutableArray array];
self.styles = [NSMutableArray array];
}
-(void)dealloc
{
[idManifest release];
[idTema release];
[nombre release];
[thumbnail release];
[thumbnailPush release];
[items release];
[colors release];
[textures release];
[styles release];
[super dealloc];
}
Now I'm getting a leak in these lines:
self.items = [NSMutableArray array];
self.colors = [NSMutableArray array];
self.textures = [NSMutableArray array];
self.styles = [NSMutableArray array];
Anyone can explain why is happening in this class and not in RDItem class now? Are the same :(
Thanks.
This is a better suggested implementation
-(void)initialize
{
self.colors = [NSMutableArray array];
self.textures = [NSMutableArray array];
self.styles = [NSMutableArray array];
}
-(void)dealloc
{
self.colors = nil;
self.textures = nil;
self.styles = nil;
}
I think that you are getting the leak because you call your initialize message more than once and you are not releasing the variables.
Normally, you should use setters or getters to access your ivars, so the appropiate operations are called (like the release message before assigning a new value on setter).
And remember to call [super dealloc] as the last instruction for your dealloc ;)
Without seeing the code where you are initialising the RDItem i can't say for sure.
But i expect that you are not releasing your previous RDItem before creating your new one. So post the code where you are creating your RDItems so we can say for sure
I think, that leak are in arrays filling code, not init. For example, you alloc and init some NSString and put it in your NSMutable array without release or autorelease it. Or something like this. Make shure that you filling your arrays right way.
Just init them when you need it. Calling alloc and init holds to arrays whose content is nil. Call alloc initWithObjects: and fill the arrays.

Using a typedef enum in my object Class

I have a People class which holds various bits of into about a person. I would like to be able to identify what kind of person this is, so I thought I would try using a typedef enum for this since I have seen it done before and it seems like the cleanest solution. But, I am unsure how to declare this, then make it into a property.
.h
typedef enum {
kPersonTypeFaculty,
kPersonTypeStaff,
kPersonTypeSearch
} personType;
#interface Person : NSObject {
NSString *nameFirst;
NSString *nameLast;
NSString *email;
NSString *phone;
NSString *room;
NSString *status;
NSString *building;
NSString *department;
NSString *imageURL;
NSString *degree;
NSString *position;
NSString *bio;
NSString *education;
}
#property (nonatomic, retain) NSString *nameFirst;
#property (nonatomic, retain) NSString *nameLast;
#property (nonatomic, retain) NSString *email;
#property (nonatomic, retain) NSString *phone;
#property (nonatomic, retain) NSString *room;
#property (nonatomic, retain) NSString *status;
#property (nonatomic, retain) NSString *building;
#property (nonatomic, retain) NSString *department;
#property (nonatomic, retain) NSString *imageURL;
#property (nonatomic, retain) NSString *degree;
#property (nonatomic, retain) NSString *position;
#property (nonatomic, retain) NSString *bio;
#property (nonatomic, retain) NSString *education;
#end
.m
#import "Person.h"
#implementation Person
#synthesize nameFirst, nameLast, email, phone, room, status, building, department, imageURL, degree, position, bio, education;
- (void)dealloc {
[nameFirst release];
[nameLast release];
[email release];
[phone release];
[room release];
[status release];
[building release];
[department release];
[imageURL release];
[degree release];
[position release];
[bio release];
[education release];
[super dealloc];
}
#end
I want to be able to do something like:
Person *person = [[[Person alloc] init] autorelease];
person.nameFirst = #"Steve";
person.nameLast = #"Johnson";
person.personType = kPersonTypeStaff;
Am I missing a crucial part of this idea?
You define it like you would for any primitive type (like int or float). When you use typedef, you are telling the compiler that this name is a type which represents this. So, you would add an instance variable with that type (I capitalized the type in my post to distinguish it from the variable or property):
personType personType;
Then add a property definition:
#property (nonatomic) personType personType;
Then you synthesize it and use it:
#synthesize personType;
self.personType = kPersonTypeStaff;
A enum type is actually some type of integer which holds all of the values of the enum. By using typedef, you can specify that this integer should be one of the constants in the enum and nothing else, and the compiler can help enforce this. But, except for the variable type, you treat it exactly the same way you would an int type.
You add the following property:
#property (nonatomic) personType personType;

Getting leaks from substringWithRange

I'm getting a leak from using substringWithRange as shown in the line of code below. I though all these functions were Autorelease and you didnt need to alloc/release them manually.
NSCFString is the object being leaked.
What is it I am doing wrong?
aLTR.drew = [substring substringWithRange:NSMakeRange(match.location+1, (match2.location-(match.location+1)))];
What I am trying to do is extract a substring and store it into my storage class. Code for that below.
#import <Foundation/Foundation.h>
#interface LeagueTableRow : NSObject
{
NSString *_teamName;
NSString *_played;
NSString *_won;
NSString *_drew;
NSString *_lost;
NSString *_goalsFor;
NSString *_goalsAgainst;
NSString *_points;
}
#property(nonatomic, copy) NSString *teamName;
#property(nonatomic, copy) NSString *played;
#property(nonatomic, copy) NSString *won;
#property(nonatomic, copy) NSString *drew;
#property(nonatomic, copy) NSString *lost;
#property(nonatomic, copy) NSString *goalsFor;
#property(nonatomic, copy) NSString *goalsAgainst;
#property(nonatomic, copy) NSString *points;
-(id)init;
#end
#import "LeagueTableRow.h"
#implementation LeagueTableRow
#synthesize teamName = _teamName;
#synthesize played = _played;
#synthesize won = _won;
#synthesize drew = _drew;
#synthesize lost = _lost;
#synthesize goalsFor = _goalsFor;
#synthesize goalsAgainst = _goalsAgainst;
#synthesize points = _points;
-(id)init
{
self = [super init];
return self;
}
-(void) dealloc
{
self.teamName = nil;
self.played = nil;
self.won = nil;
self.drew = nil;
self.lost = nil;
self.goalsFor = nil;
self.goalsAgainst = nil;
self.points = nil;
[super dealloc];
}
#end
I'm quiet surprised I got some leaks I though I was managing the memory quiet tidily.
Thanks for the advice and tips.
-Code
In your dealloc, simply release all the string ivars:
[_teamName release];
etc...
Alternatively, you could do:
[self.teamName release];
etc...
I prefer to use the ivars directly, in such situations.