initialization with a nibFIle failed - iphone

I have a problem.
I try to initialize a variabile in a classViewController created inside a xib file.
I try with the code below but when i append a object to array, these array isn't initialized.
Can you help me?
thanks and sorry for my english.
#import <UIKit/UIKit.h>
#interface AccelerometroViewController : UIViewController <UIAccelerometerDelegate, UITextFieldDelegate, UIAlertViewDelegate>{
//.....
NSMutableArray *arrayPosizioni;
NSMutableArray *arrayPosizioniCorrenti;
NSString *nomePosizioneCorrente;
}
-(IBAction)salvaPosizione;
//...
#property (nonatomic, assign) NSMutableArray *arrayPosizioni;
#property (nonatomic, assign) NSMutableArray *arrayPosizioniCorrenti;
#property (nonatomic, assign) NSString *nomePosizioneCorrente;
#end
#import "AccelerometroViewController.h"
#import "Position.h"
#implementation AccelerometroViewController
float actualX;
float actualY;
float actualZ;
#synthesize arrayPosition;
#synthesize arrayCurrentPosition;
#synthesize nameCurrentPosition;
-(id)init {
self = [super init];
if (self != nil) {
arrayPosition = [[NSMutableArray alloc]init];
arrayCurrentPosition = [[NSMutableArray alloc]init];
nameCurrentPosition = [NSString stringWithFormat:#"noPosition"];
actualX = 0;
actualY = 0;
actualZ = 0;
}
return self;
}
-(void)updateTextView:(NSString*)nomePosizione
{
NSString *string = [NSString stringWithFormat:#"%#", nameCurrentPosition];
textEvent.text = [textEvent.text stringByAppendingString:#"\n"];
textEvent.text = [textEvent.text stringByAppendingString:string];
}
-(IBAction)savePosition{
Posizione *newPosition;
newPosition = [[Position alloc]init];
if([newPosition setValue:(NSString*)fieldNomePosizione.text:(float)actualX:(float)actualY:(float)actualZ]){
//setValue is a method of Position. I'm sure that this method is correct
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Salvataggio Posizione" message:#"Posizione salvata con successo" delegate:self cancelButtonTitle:#"Cancel" otherButtonTitles:nil];
[alert show];
[alert release];
[arrayPosition addObject:newPosition];
}
else{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Salvataggio osizione" message:#"Errore nel salvataggio" delegate:self cancelButtonTitle:#"Cancel" otherButtonTitles:nil];
[alert show];
[alert release];
}
}
- (void) initialise {
arrayPosition = [[NSMutableArray alloc] init];
arrayCurrentPosition = [[NSMutableArray alloc] init];
nameCurrentPosition = #"noPosition";
actualX = 0;
actualY = 0;
actualZ = 0;
}
- (id)initWithNibName:(NSString *)nibName bundle:(NSBundle *)nibBundle {
if (self = [super initWithNibName:nibName bundle:bundle]) {
[self initialise];
}
}

In addition to Felix's comment regarding the mis-naming, your properties are wrong too. Objects need to be retained or copied, not assigned (in most cases) so that you're certain their value won't go away. You need to have ownership of them. As such I would use the following:
#property (nonatomic, readwrite, retain) NSMutableArray *arrayPosition;
#property (nonatomic, readwrite, retain) NSMutableArray *arrayCurrentPosition;
#property (nonatomic, readwrite, copy) NSString *nameCurrentPosition;
Then, since you've retained something you're responsible for releasing it. As such you'll need a dealloc method to do that.
-(void)dealloc {
self.arrayPosition = nil;
self.arrayCurrentPosition = nil;
self.nameCurrentPosition = nil;
[super dealloc];
}

Related

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.

I am unable to copy my NSMutable array to appDelegate_iPhone array(Universal app)

Actually I have parsed an XML and store URL's of images as an NSMutableArray object, but I want this array to be used in another ViewController (to give to UIImage in UIImageView to show Images at runtime), so I am trying to copy that Mutable array to myAppDelegate_iPhone's NSMutableArray. And I want to again copy that Appdelegate's array to my next or other ViewControllers NSMutableArray.
so can anyone help me out pleaseeeeee? Here is my code :-
code:-
#class FirstViewController;
#interface AppDelegate_iPhone : NSObject <UIApplicationDelegate> {
UIWindow *window;
FirstViewController *viewController;
NSMutableArray *logoArray;
}
#property (nonatomic, retain) IBOutlet UIWindow *window;
#property (nonatomic, retain) NSMutableArray *logoArray;
#end
#import "AppDelegate_iPhone.h"
#import "FirstViewController.h"
#import "ParsingViewController.h"
#implementation AppDelegate_iPhone
#synthesize window,logoArray;
#pragma mark -
#pragma mark Application lifecycle
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.
viewController = [[FirstViewController alloc]initWithNibName:#"FirstViewController" bundle:nil];
viewController.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
NSURL *url = [[NSURL alloc] initWithString:#"http://litofinter.es.milfoil.arvixe.com/displayxml1.aspx"];
NSXMLParser *xmlParser = [[NSXMLParser alloc] initWithContentsOfURL:url];
//Initialize the delegate.
ParsingViewController *parser = [[ParsingViewController alloc] init];
//Set delegate
[xmlParser setDelegate:parser];
//Start parsing the XML file.
BOOL success = [xmlParser parse];
if(success)
NSLog(#"No Errors");
else
NSLog(#"Error Error Error!!!");
logoArray = [[NSMutableArray alloc]init];
[self.window addSubview:viewController.view];
[self.window makeKeyAndVisible];
return YES;
}
// dealloc done
#end
#class Litofinter,AppDelegate_iPhone;
#interface ParsingViewController : NSObject<NSXMLParserDelegate> {
NSString *myString;
NSMutableArray *myMutableArray;
Litofinter *obj;
NSString *currentElement;
AppDelegate_iPhone *appDelegate;
}
#import "ParsingViewController.h"
#import "Litofinter.h"
#import "AppDelegate_iPhone.h"
#implementation ParsingViewController
#synthesize myMutableArray, myString;
-(id)init{
if(self == [super init]){
myMutableArray = [[NSMutableArray alloc] init];
}
return self;
}
- (void)parserDidStartDocument:(NSXMLParser *)parser
{
//myMutableArray = [[NSMutableArray alloc]init];
}
// Parsing done here
- (void)parserDidEndDocument:(NSXMLParser *)parser
{
appDelegate = (AppDelegate_iPhone *)[[UIApplication sharedApplication] delegate];
//UIApplication *app = [UIApplication sharedApplication];
//appDelegate=app.delegate;
appDelegate.logoArray = [[NSMutableArray alloc]initWithArray:myMutableArray];
NSLog(#"appDelegate.logoArray count %d",[appDelegate.logoArray count]);
for (Litofinter *lito in appDelegate.logoArray) {
NSLog(#"Array Elements :----- %#",lito.cLogo);
}
}
#end
#import <UIKit/UIKit.h>
#class AppDelegate_iPhone,Litofinter,ParsingViewController;
#interface FirstViewController : UIViewController {
NSMutableArray *array;
//Litofinter *lito;
NSString *logoString;
AppDelegate_iPhone *appDelegate;
ParsingViewController *obj;
}
#end
#import "FirstViewController.h"
#import "AppDelegate_iPhone.h"
#import "Litofinter.h"
#import "ParsingViewController.h"
#implementation FirstViewController
-(id)init{
if(self == [super init]){
obj = [[ParsingViewController alloc] init];
array = [[NSArray alloc] initWithArray: obj.myMutableArray];
}
return self;
}
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
[super viewDidLoad];
int x=5,y=10;
appDelegate = (AppDelegate_iPhone *)[[UIApplication sharedApplication] delegate];
// UIApplication *app = [UIApplication sharedApplication];
// appDelegate=app.delegate;
NSLog(#"delegate Array ====== %d",[appDelegate.logoArray count]);
NSLog(#"New Array ====== %d",[obj.myMutableArray count]);
/*
array = [[NSMutableArray alloc]initWithArray:appDelegate.logoArray];
NSLog(#"array at 0 ===== %#",[array objectAtIndex:0]);
for (Litofinter *lito1 in obj.myMutableArray) {
NSLog(#"Array Elements in Lito1 are :------------- %#",lito1.cLogo);
}
for (Litofinter *lito2 in array) {
NSLog(#"Array Elements in Lito1 are :------------- %#",lito2.cLogo);
}
*/
for (Litofinter *lito in obj.myMutableArray) {
//for (int i=0; i<[appDelegate.logoArray count]; i++) {
// lito.cLogo = [array objectAtIndex:i];
NSLog(#"%#",lito.cLogo);
UIImage *imageFromUrl = [UIImage imageWithContentsOfFile:[NSURL fileURLWithPath:lito.cLogo]];
UIImageView *imgView = [[UIImageView alloc] initWithImage:imageFromUrl];
[imgView setFrame:CGRectMake(x, y, 196, 90)];
[self.view addSubview:imgView];
UITapGestureRecognizer *tgr = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(onTapImage)];
[imgView addGestureRecognizer:tgr];
// [tgr release];
//Do the rest of your operations here, don't forget to release the UIImageView
x = x + 200;
}
}
-(void)onTapImage
{
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"Message from mAc" message:#"Trail" delegate:self cancelButtonTitle:#"Cancel" otherButtonTitles:#"Ok",nil];
[alert show];
}
- (void)dealloc {
[super dealloc];
}
#end
You can use this.
UIImage *imageFromUrl = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:lito.cLogo]]];

Debugger message

I do webservice requests with a UISegmentedControl, when I change segmentedItem and request fast the application crashes with this message:
[Session started at 2011-05-12
10:58:50 +0200.] Terminating in
response to SpringBoard's termination.
[Session started at 2011-05-12
11:06:31 +0200.] GNU gdb
6.3.50-20050815 (Apple version gdb-1516) (Fri Feb 11 06:19:43 UTC
2011) Copyright 2004 Free Software
Foundation, Inc. GDB is free software,
covered by the GNU General Public
License, and you are welcome to change
it and/or distribute copies of it
under certain conditions. Type "show
copying" to see the conditions. There
is absolutely no warranty for GDB.
Type "show warranty" for details. This
GDB was configured as
"--host=i386-apple-darwin
--target=arm-apple-darwin".tty /dev/ttys001 Loading program into
debugger… Program loaded. target
remote-mobile
/tmp/.XcodeGDBRemote-239-58 Switching
to remote-macosx protocol mem 0x1000
0x3fffffff cache mem 0x40000000
0xffffffff none mem 0x00000000 0x0fff
none run Running… [Switching to thread
11779] [Switching to thread 11779]
sharedlibrary apply-load-rules all
continue Program received signal:
“SIGKILL”. warning: Unable to read
symbols for
/Developer/Platforms/iPhoneOS.platform/DeviceSupport/4.3.3
(8J2)/Symbols/Developer/usr/lib/libXcodeDebuggerSupport.dylib
(file not found). kill quit
The Debugger has exited with status
0.(gdb)
Does anybody have an idea of how can I fix this?
Is this a problem because I'm not using NSOperationQueue?
And if so any suggestions how I can fix this would be very welcomed.
I can not find any memory leaks when running.
Next time I ran it this message got logged:
Program received signal: “EXC_BAD_ACCESS”.
warning: Unable to read symbols for /Developer/Platforms/iPhoneOS.platform/DeviceSupport/4.3.3 (8J2)/Symbols/Developer/usr/lib/libXcodeDebuggerSupport.dylib (file not found).
(gdb)
Here is the code for starting the connection:
Class header ServiceGetChildren:
#import <Foundation/Foundation.h>
#class Authentication;
#class AttendanceReportViewController;
#interface ServiceGetChildren : NSObject {
Authentication *authentication;
AttendanceReportViewController *attendanceReportViewController;
NSString *username;
NSString *password;
NSMutableString *authenticationString;
NSString *encodedLoginData;
NSMutableData *responseData;
NSMutableArray *childrensArray;
}
#property (nonatomic, retain) NSString *username;
#property (nonatomic, retain) NSString *password;
#property (nonatomic, retain) NSMutableString *authenticationString;
#property (nonatomic, retain) NSString *encodedLoginData;
#property (nonatomic, retain) NSMutableData *responseData;
#property (nonatomic, retain) NSMutableArray *childrensArray;
- (void)startService:(NSURL *)url :(NSString *)method withParent:(UIViewController *)controller;
#end
Class handling the request:
#import "ServiceGetChildren.h"
#import "JSON.h"
#import "Base64.h"
#import "AttendanceReportViewController.h"
#import "Authentication.h"
#implementation ServiceGetChildren
#synthesize appDelegate;
#synthesize username;
#synthesize password;
#synthesize authenticationString;
#synthesize encodedLoginData;
#synthesize responseData;
#synthesize childrensArray;
- (id) init {
if ((self = [super init])) {
}
return self;
}
- (void)startService:(NSURL *)url :(NSString *)method withParent:(UIViewController *)controller {
username = appDelegate.username;
password = appDelegate.password;
attendanceReportViewController = (AttendanceReportViewController *)controller;
Authentication *auth = [[Authentication alloc] init];
authenticationString = (NSMutableString*)[#"" stringByAppendingFormat:#"%#:%#", username, password];
encodedLoginData = [auth encodedAuthentication:authenticationString];
[auth release];
// Setup up the request with the url
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL: url
cachePolicy: NSURLRequestReloadIgnoringCacheData
timeoutInterval: 20.0];
[request setHTTPMethod:method];
[request setValue:[NSString stringWithFormat:#"Basic %#", encodedLoginData] forHTTPHeaderField:#"Authorization"];
NSURLConnection *connection = [[NSURLConnection alloc]initWithRequest:request delegate:self];
// Display the network indicator when the connection request started
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
// Check that the NSURLConnection was successful and then initialize the responseData
if(connection) {
NSLog(#"Connection made");
responseData = [[NSMutableData data] retain];
}
else {
NSLog(#"Connection could not be made");
}
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
[responseData setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[responseData appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSLog(#"Connection finished loading.");
// Dismiss the network indicator when connection finished loading
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
// Parse the responseData of json objects retrieved from the service
SBJSON *parser = [[SBJSON alloc] init];
NSString *jsonString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSDictionary *jsonData = [parser objectWithString:jsonString error:nil];
NSMutableArray *array = [jsonData objectForKey:#"Children"];
childrensArray = [NSMutableArray arrayWithArray:array];
// Callback to AttendanceReportViewController that the responseData finished loading
[attendanceReportViewController loadChildren];
[connection release];
[responseData release];
[jsonString release];
[parser release];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
NSLog(#"Connection failure.");
NSLog(#"ERROR%#", error);
// Dismiss the network indicator when connection failure occurred
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
[connection release];
// Inform the user that the server was unavailable
}
- (void) dealloc {
[attendanceReportViewController release];
[super dealloc];
}
Class header for AttendanceReportViewController:
#import <UIKit/UIKit.h>
#class ServiceGetGroups;
#class ServiceGetChildren;
#class DetailViewController;
#interface AttendanceReportViewController : UIViewController <UITableViewDataSource, UITableViewDelegate> {
ServiceGetGroups *serviceGetGroups;
ServiceGetChildren *serviceGetChildren;
DetailViewController *detailViewController;
UISegmentedControl *segmentedControl;
IBOutlet UIToolbar *groupsToolbar;
NSMutableArray *btnArray;
NSInteger index;
IBOutlet UITableView *theTableView;
IBOutlet UILabel *attendanceLabel;
IBOutlet UILabel *abscentLabel;
IBOutlet UILabel *totalLabel;
NSMutableDictionary *selectRequestDictionary;
NSMutableDictionary *selectNameDictionary;
NSMutableArray *groupsArray;
NSMutableArray *childrensArray;
NSDictionary *childrensDictionary;
NSURL *url;
}
#property (nonatomic, retain) ServiceGetGroups *serviceGetGroups;
#property (nonatomic, retain) ServiceGetChildren *serviceGetChildren;
#property (nonatomic, retain) DetailViewController *detailViewController;
#property (nonatomic, retain) IBOutlet UIToolbar *groupsToolbar;
#property (nonatomic, retain) IBOutlet UITableView *theTableView;
#property (nonatomic, retain) IBOutlet UILabel *attendanceLabel;
#property (nonatomic, retain) IBOutlet UILabel *abscentLabel;
#property (nonatomic, retain) IBOutlet UILabel *totalLabel;
#property (nonatomic, retain) UISegmentedControl *segmentedControl;
#property (nonatomic) NSInteger index;
#property (nonatomic, retain) NSMutableArray *btnArray;
#property (nonatomic, retain) NSMutableDictionary *selectRequestDictionary;
#property (nonatomic, retain) NSMutableDictionary *selectNameDictionary;
#property (nonatomic, retain) NSMutableArray *groupsArray;
#property (nonatomic, retain) NSMutableArray *childrensArray;
#property (nonatomic, retain) NSDictionary *childrensDictionary;
#property (nonatomic, retain) NSURL *url;
- (void)setupSegmentedControl;
- (void)requestGroups;
- (void)requestChildren:(NSNumber *)groupId;
- (void)loadGroups;
- (void)loadChildren;
#end
Class that the Uses the UISegmentedControl:
#import "JSON.h"
#import "AttendanceReportViewController.h"
#import "CustomCellViewController.h"
#import "DetailViewController.h"
#import "ServiceGetGroups.h"
#import "ServiceGetChildren.h"
#import "Group.h"
#import "Child.h"
#implementation AttendanceReportViewController
#synthesize serviceGetGroups;
#synthesize serviceGetChildren;
#synthesize detailViewController;
#synthesize segmentedControl;
#synthesize groupsToolbar;
#synthesize index;
#synthesize btnArray;
#synthesize theTableView;
#synthesize attendanceLabel;
#synthesize abscentLabel;
#synthesize totalLabel;
#synthesize selectRequestDictionary;
#synthesize selectNameDictionary;
#synthesize groupsArray;
#synthesize childrensArray;
#synthesize childrensDictionary;
#synthesize url;
#pragma mark -
#pragma mark View lifecycle
// The designated initializer. Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization.
}
return self;
}
- (void)requestGroups {
NSURL *groupsURL = [NSURL URLWithString:#"http://services/groups"];
[serviceGetGroups startService:groupsURL :#"GET" withParent:self];
}
- (void)requestChildren:(NSNumber *)groupId {
NSLog(#"%#", groupId);
NSString *baseURL = #"http://services/group/";
NSString *method = [NSString stringWithFormat:#"%#%#", groupId, #"/children"];
NSString *theURL = [NSString stringWithFormat:#"%#%#", baseURL, method];
self.url = [NSURL URLWithString:theURL];
NSLog(#"%#", self.url);
[serviceGetChildren startService:self.url :#"GET" withParent:self];
}
- (void)loadGroups {
// Retrieve a array with dictionaries of groups from ServiceGetGroups
self.groupsArray = [[serviceGetGroups.groupsArray copy] autorelease];
// The array to hold segmentedItems for the segmentedControl, representing groups buttons
btnArray = [NSMutableArray arrayWithObjects: #"Alla", nil];
for (NSDictionary *groupDict in groupsArray) {
// Add each groups name to the btnArray as segmentedItems for the segmentedControl
[btnArray addObject:[groupDict objectForKey:#"Name"]];
}
// Create a new NSMutableDictionary with group names as keys and group id´s as values
// used for reference to segementedControl items to make request to serviceGetChildren
self.selectRequestDictionary = [NSMutableDictionary dictionary];
for (NSDictionary *dict in groupsArray) {
[selectRequestDictionary setObject:[dict objectForKey:#"Id"] forKey:[dict objectForKey:#"Name"]];
}
// Create a new NSMutableDictionary with group id´s as keys and group names as values
// used for retrieving a groupName from a passed id
self.selectNameDictionary = [NSMutableDictionary dictionary];
for (NSDictionary *dict in groupsArray) {
[selectNameDictionary setObject:[dict objectForKey:#"Name"] forKey:[dict objectForKey:#"Id"]];
}
[self setupSegmentedControl];
}
- (void)setupSegmentedControl {
// Setup the UISegmentedControl as groups buttons
segmentedControl = nil;
segmentedControl = [[UISegmentedControl alloc] initWithItems:btnArray];
segmentedControl.tintColor = [UIColor darkGrayColor];
segmentedControl.selectedSegmentIndex = 0;
segmentedControl.autoresizingMask = UIViewAutoresizingFlexibleWidth;
segmentedControl.segmentedControlStyle = UISegmentedControlStyleBar;
segmentedControl.frame = CGRectMake(0, 0, 300, 30);
// Setup the target and actions for the segmentedControl
[segmentedControl addTarget:self
action:#selector(selectGroup:)
forControlEvents:UIControlEventValueChanged];
// Add the UISegmentedControl as a UIBarButtonItem subview to the UIToolbar
UIBarButtonItem *segmentedItem = [[[UIBarButtonItem alloc] initWithCustomView:segmentedControl] autorelease];
UIBarButtonItem *flexSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
NSArray *groupsButtons = [NSArray arrayWithObjects:flexSpace, segmentedItem, flexSpace, nil];
[groupsToolbar setItems:groupsButtons];
[flexSpace release];
}
- (void)loadChildren {
// Retrieve a array with dictionaries of children from ServiceGetChildren
self.childrensArray = [[serviceGetChildren.childrensArray copy] autorelease];
// TODO create seperate method - Setup compilation bar values
int total = [childrensArray count];
totalLabel.text = [NSString stringWithFormat:#"%d", total];
[theTableView reloadData];
}
// Handles UIControlEventValueChanged for UISegmentedControl, retreives the name and id for a selected group
- (void)selectGroup:(UISegmentedControl *)theSegmentedControl {
NSString *selectedGroup = [segmentedControl titleForSegmentAtIndex: [segmentedControl selectedSegmentIndex]];
NSNumber *selectedId = [selectRequestDictionary objectForKey:selectedGroup];
// Persist the selectedSegmentIndex when view switches to detaildView
index = [segmentedControl selectedSegmentIndex];
// Request children based on the selected groupId
[self requestChildren:selectedId];
}
- (void)viewDidLoad {
[self requestGroups];
[super viewDidLoad];
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
//self.navigationItem.rightBarButtonItem = self.editButtonItem;
}
#pragma mark -
#pragma mark Table view data source
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
// Return the number of rows in the section.
return [childrensArray count];
}
// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"CustomCell";
// Load from nib
CustomCellViewController *cell = (CustomCellViewController *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
NSArray *topLevelObjects = [[NSBundle mainBundle]
loadNibNamed:#"CustomCellView"
owner:nil
options:nil];
for (id currentObject in topLevelObjects) {
if ([currentObject isKindOfClass:[UITableViewCell class]]) {
cell = (CustomCellViewController *) currentObject;
break;
}
}
}
// Set up a children dictionary for easy retrieving specific values to display in the UITableView
childrensDictionary = [childrensArray objectAtIndex:indexPath.row];
NSNumber *idForName = [childrensDictionary valueForKey:#"GroupId"];
NSString *name = [NSString stringWithFormat:#"%# %#",
[childrensDictionary valueForKey:#"Firstname"],
[childrensDictionary valueForKey:#"Surname"]];
NSString *group = [NSString stringWithFormat:#"%#",
[selectNameDictionary objectForKey:idForName]];
cell.childNameLabel.text = name;
cell.groupNameLabel.text = group;
cell.scheduleLabel.text = #"Schema";
cell.deviationLabel.text = #"Avvikelse";
return cell;
}
#pragma mark -
#pragma mark Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
// Navigation logic may go here. Create and push the detailedViewController.
if (detailViewController == nil) {
DetailViewController *_detailViewcontroller = [[DetailViewController alloc]
initWithNibName:#"DetailView" bundle:nil];
self.detailViewController = _detailViewcontroller;
[_detailViewcontroller release];
}
childrensDictionary = [childrensArray objectAtIndex:indexPath.row];
NSNumber *idForName = [childrensDictionary valueForKey:#"GroupId"];
NSString *group = [NSString stringWithFormat:#"%#",
[selectNameDictionary objectForKey:idForName]];
[self.detailViewController initWithDetailsSelected:childrensDictionary:group];
[self.navigationController pushViewController:detailViewController animated:YES];
}
#pragma mark -
#pragma mark Memory management
- (void)didReceiveMemoryWarning {
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Relinquish ownership any cached data, images, etc. that aren't in use.
}
- (void)viewDidUnload {
// Relinquish ownership of anything that can be recreated in viewDidLoad or on demand.
// For example: self.myOutlet = nil;
segmentedControl = nil;
}
- (void)dealloc {
[segmentedControl release];
[groupsArray release];
[childrensArray release];
[detailViewController release];
[super dealloc];
}
#end
OK here we go. First of all, I could not test the code, so I need your feedback.
The main problem with this class is, you only have one instance, which you reuse every time you hit the segmented control. This leads to creation of new instances of the NSURLConnection. So let's correct a bit in the header. I changed the NSString properties to copy. Have a look at this Q&A to know why, however this is not important for the improvement, just wanted to let you know.
I've removed Authentication *authentication; looked like you don't use it.
Added NSURLConnection as property so we keep a reference on it.
Header file
#class Authentication;
#class AttendanceReportViewController;
#interface ServiceGetChildren : NSObject {
AttendanceReportViewController *attendanceReportViewController;
NSString *username;
NSString *password;
NSMutableString *authenticationString;
NSString *encodedLoginData;
NSMutableData *responseData;
NSMutableArray *childrensArray;
NSURLConnection *connection;
}
#property (nonatomic, copy) NSString *username;
#property (nonatomic, copy) NSString *password;
#property (nonatomic, retain) NSMutableString *authenticationString;
#property (nonatomic, copy) NSString *encodedLoginData;
#property (nonatomic, retain) NSMutableData *responseData;
#property (nonatomic, retain) NSMutableArray *childrensArray;
#property (nonatomic, retain) NSURLConnection *connection
- (void)startService:(NSURL *)url :(NSString *)method withParent:(UIViewController *)controller;
#end
Next comes the Implementation file. I only altered the startService method and dealloc.
If you declare properties, use them :) Have a look at this Q&A for some explanations on synthesized properties.
Always release what you own, so I added release code in the dealloc.
Cancel the previous request!!! If there is none, the message is sent to nil, which causes no harm.
Implementation file
- (void)startService:(NSURL *)url:(NSString *)method withParent:(UIViewController *)controller
{
self.username = appDelegate.username;
self.password = appDelegate.password;
[connection cancel];
attendanceReportViewController = (AttendanceReportViewController *)controller;
Authentication *auth = [[Authentication alloc] init];
authenticationString = (NSMutableString *)[#"" stringByAppendingFormat:#"%#:%#", username, password];
self.encodedLoginData = [auth encodedAuthentication:authenticationString];
[auth release];
// Setup up the request with the url
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestReloadIgnoringCacheData
timeoutInterval:20.0];
[request setHTTPMethod:method];
[request setValue:[NSString stringWithFormat:#"Basic %#", encodedLoginData] forHTTPHeaderField:#"Authorization"];
self.connection = [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
// Display the network indicator when the connection request started
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
// Check that the NSURLConnection was successful and then initialize the responseData
if (connection) {
NSLog(#"Connection made");
self.responseData = [NSMutableData data];
} else {
NSLog(#"Connection could not be made");
}
}
...
- (void) dealloc
{
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
[connection cancel];
[connection release];
[appDelegate release];
[responseData release];
[username release];
[password release];
[authenticationString release];
[encodedLoginData release];
[responseData release];
[childrensArray release];
[super dealloc];
}
Hope this helps for the next steps. However I think we will have to work a bit on the solution until it's final.

Obj-C UIActionSheet Memory Leaks iPhone

I'm coding a popup screen that will show up if a the value for mulValue in the settings is nil. Here is the code:
#import "FirstViewController.h"
#implementation FirstViewController
#synthesize myHelpfile = ivHelpfile; //UIAlertView
#synthesize myAboutfile = ivAboutfile; //UIAlertView
#synthesize myNoarea = ivNoarea; //UIAlertView
#synthesize myMap = ivMap; //UIImageView
#synthesize myAreapick = ivAreapick; //UIActionSheet
#synthesize myAdvancedmode = ivAdvancedmode; //NSString
#synthesize myAreaset = ivAreaset; //NSString
#synthesize myAreaarray = ivAreaarray; //NSArray
#synthesize appSettingsViewController, settingsViewController;
- (void)viewDidLoad {
[super viewDidLoad];
self.title = #"Wildlife";
NSString *area = [[NSUserDefaults standardUserDefaults] stringForKey:#"mulValue"];
[self setMyAreaset:area];
if ([self myAreaset] == nil) { //check if any region is selected. If not, push UIActionsheet
NSArray *array = [[NSArray alloc] initWithObjects: // creating array for different regions
[NSString stringWithString:#"Region 1"],
[NSString stringWithString:#"Region 2"],
[NSString stringWithString:#"Region 3"],
[NSString stringWithString:#"Region 4"],
[NSString stringWithString:#"Region 5"],
[NSString stringWithString:#"Region 6"],nil];
[self setMyAreaarray:array];
[array release], array = nil;
NSLog(#"Built areaselectArray");
NSLog(#"Values of areaselectArray are %#",[self myAreaarray]);
UIActionSheet *areaselect = [[UIActionSheet alloc] initWithTitle:#"Select your current area" //creation of popup Area Selection
delegate:self
cancelButtonTitle:nil
destructiveButtonTitle:nil
otherButtonTitles:nil];
[self setMyAreapick:areaselect];
[areaselect release], areaselect = nil;
int countarray = [[self myAreaarray] count];
for (int i = 0; i < countarray; i++) { //building list from array
[[self myAreapick] addButtonWithTitle:[[self myAreaarray] objectAtIndex:i]];
}
[[self myAreapick] addButtonWithTitle:#"Cancel"];
[self myAreapick].cancelButtonIndex = countarray;
[[self myAreapick] showInView:self.view];//show the general UIActionSheet instance
NSLog(#"Out of viewDidLoad");
}
else {
NSLog(#"Area is %#, no need for areaselectArray",area);
}
}
-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger )buttonIndex
{
int countarray = [[self myAreaarray] count];
if (buttonIndex != countarray) { //cancel button is at countarray, so for anything that is not cancel, do:
NSString *area = [[self myAreaarray] objectAtIndex:(buttonIndex)];
[self setMyAreaset:area];
[[NSUserDefaults standardUserDefaults] setObject:[self myAreaset] forKey:#"mulValue"];
[[NSUserDefaults standardUserDefaults] synchronize]; //sync
NSLog(#"Released areaselectArray");
}
else {
}
}
And in my FirstViewController.h I have:
#interface FirstViewController : UIViewController <UIActionSheetDelegate, IASKSettingsDelegate, UIAlertViewDelegate> {
UIAlertView *ivHelpfile;
UIAlertView *ivAboutfile;
UIAlertView *ivNoarea;
UIActionSheet *ivAreapick;
UIImageView *ivMap;
NSString *ivAdvancedmode;
NSString *ivAreaset;
NSArray *ivAreaarray;
}
#property(nonatomic, retain) UIAlertView *myHelpfile;
#property(nonatomic, retain) UIAlertView *myAboutfile;
#property(nonatomic, retain) UIAlertView *myNoarea;
#property(nonatomic, retain) UIActionSheet *myAreapick;
#property(nonatomic, retain) UIImageView *myMap;
#property(nonatomic, copy) NSString *myAdvancedmode;
#property(nonatomic, copy) NSString *myAreaset;
#property(nonatomic, retain) NSArray *myAreaarray;
When I run my app in the simulator with Instruments running, I get a memory leak whenever I scroll the list of rows (as built by [self myAreaarray]) and release my finger. The weird thing is, it has not really done anything else at that point. The main view is loaded, but it would be strange that that would cause a memory leak based on scrolling through the list.
The leaks I get in Instruments are the following:
_NSCFType 48 bytes CoreGraphics CGTypeCreateInstanceWithAllocator
UIDeviceWhiteColor 16 bytes UIKit +[UIColor allocWithZone:]
When I scroll through the list again, more of those errors show up. It looks like I'm allocating something and not releasing it (while I'm scrolling the list?), but I can't find it at this point.
Any help would be appreciated!
I'm seeing it as well, even abstracting all your app code from it:
UIActionSheet *as = [[UIActionSheet alloc] initWithTitle:#"Test" delegate:nil cancelButtonTitle:nil destructiveButtonTitle:nil otherButtonTitles:nil];
for (int i = 0; i < 100; i++) {
[as addButtonWithTitle:[NSString stringWithFormat:#"Button %i", i]];
}
as.cancelButtonIndex = 99;
as.destructiveButtonIndex = 0;
[as showInView:self.view];
[as release];
When running through Instruments memory leak profiler, each display of the action sheet yieds 6 UIDeviceWhiteColor leaks and 4 CGColor leaks. Looks to me like this is a bug in UIKit.

Initialization problem

I have a problem.
This is my code.
When i try to use the IBAction SavePosition the "arrayPosition" isn't update.
Else if i initialize the "arrayPosition" in "SavePosition" the value is stored in the array.
Why this anomaly?
#import <UIKit/UIKit.h>
#interface AccelerometroViewController : UIViewController <UIAccelerometerDelegate, UITextFieldDelegate, UIAlertViewDelegate>{
//.....
NSMutableArray *arrayPosizioni;
NSMutableArray *arrayPosizioniCorrenti;
NSString *nomePosizioneCorrente;
}
-(IBAction)salvaPosizione;
//...
#property (nonatomic, assign) NSMutableArray *arrayPosizioni;
#property (nonatomic, assign) NSMutableArray *arrayPosizioniCorrenti;
#property (nonatomic, assign) NSString *nomePosizioneCorrente;
#end
#import "AccelerometroViewController.h"
#import "Position.h"
#implementation AccelerometroViewController
float actualX;
float actualY;
float actualZ;
#synthesize arrayPosition;
#synthesize arrayCurrentPosition;
#synthesize nameCurrentPosition;
-(id)init {
self = [super init];
if (self != nil) {
arrayPosition = [[NSMutableArray alloc]init];
arrayCurrentPosition = [[NSMutableArray alloc]init];
nameCurrentPosition = [NSString stringWithFormat:#"noPosition"];
actualX = 0;
actualY = 0;
actualZ = 0;
}
return self;
}
-(void)updateTextView:(NSString*)nomePosizione
{
NSString *string = [NSString stringWithFormat:#"%#", nameCurrentPosition];
textEvent.text = [textEvent.text stringByAppendingString:#"\n"];
textEvent.text = [textEvent.text stringByAppendingString:string];
}
-(IBAction)savePosition{
Posizione *newPosition;
newPosition = [[Position alloc]init];
if([newPosition setValue:(NSString*)fieldNomePosizione.text:(float)actualX:(float)actualY:(float)actualZ]){
//setValue is a method of Position. I'm sure that this method is correct
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Salvataggio Posizione" message:#"Posizione salvata con successo" delegate:self cancelButtonTitle:#"Cancel" otherButtonTitles:nil];
[alert show];
[alert release];
[arrayPosition addObject:newPosition];
}
else{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Salvataggio osizione" message:#"Errore nel salvataggio" delegate:self cancelButtonTitle:#"Cancel" otherButtonTitles:nil];
[alert show];
[alert release];
}
}
Whats going on?
I bet you're creating your view controller inside a xib file?
If you set a breakpoint inside your init method on the line
arrayPosition = [[NSMutableArray alloc]init];
I bet it never runs. This means that when you get to the line
[arrayPosition addObject:newPosition];
arrayPosition is still nil so nothing happens.
How to fix it?
If you're initializing a UIViewController it's either called inside initWithNibName:bundle: if you've created it in code or in initWithCoder: if it's created inside a xib file.
You need to do something like this :
- (void) initialise {
arrayPosition = [[NSMutableArray alloc] init];
arrayCurrentPosition = [[NSMutableArray alloc] init];
nameCurrentPosition = #"noPosition";
actualX = 0;
actualY = 0;
actualZ = 0;
}
- (id)initWithNibName:(NSString *)nibName bundle:(NSBundle *)nibBundle {
if (self = [super initWithNibName:nibName bundle:bundle]) {
[self initialise];
}
return self;
}
- (id)initWithCoder:(NSCoder *)decoder {
if (self = [super initWithCoder:decoder]) {
[self initialise];
}
return self;
}
This will call initailise regardless of how the view controller is created.
This:
[newPosition setValue:(NSString*)fieldNomePosizione.text:(float)actualX:(float)actualY:(float)actualZ]
... is gibberish. I don't even see how it compiles. I assume its a typo. However, if the function does not return a boolean it will return a void pointer and always evaluate to false so the block is never called.
More generally, your problem is most likely that you are not using the self.propertyName notation to refer to your properties so they are not being retained. E.g.
[arrayPosition addObject:newPosition];
should be:
[self.arrayPosition addObject:newPosition];
... as should all other references to arrayPosition in the code.