Search Results

Search found 1263 results on 51 pages for 'retain'.

Page 8/51 | < Previous Page | 4 5 6 7 8 9 10 11 12 13 14 15  | Next Page >

  • How to use NSMutableDictionary to store and retrieve data

    - by TechFusion
    I have created Window Based application and tab bar controller as root controller. My objective is to store Text Field data values in one tab bar VC and will be accessible and editable by other VC and also retrievable when application start. I am looking to use NSMutableDictionary class in AppDelegate so that I can access stored Data Values with keys. //TestAppDelegate.h extern NSString *kNamekey ; extern NSString *kUserIDkey ; extern NSString *kPasswordkey ; @interface TestAppDelegate :NSObject{ UIWindow *window; IBOutlet UITabBarController *rootController; NSMutableDictionary *outlineData ; } @property(nonatomic,retain)IBOutlet UIWindow *window; @property(nonatomic,retain)IBOutlet UITabBarController *rootController; @property(nonatomic,retain) NSMutableDictionary *outlineData ; @end //TestAppDelegate.m import "TestAppDelegate.h" NSString *kNamekey =@"Namekey"; NSString *kUserIDkey =@"UserIDkey"; NSString *kPasswordkey =@"Passwordkey"; @implemetation TestAppDelegate @synthesize outlineData ; -(void)applicationDidFinishLaunching:(UIApplication)application { NSMutableDictionary *tempMutableCopy = [[[NSUserDefaults standardUserDefaults] objectForKey:kRestoreLocationKey] mutableCopy]; self.outlineData = tempMutableCopy; [tempMutableCopy release]; if(outlineData == nil){ NSString *NameDefault = NULL; NSString *UserIDdefault= NULL; NSString *Passworddefault= NULL; NSMutableDictionary *appDefaults = [NSMutableDictionary dictionaryWithObjectsAndKeys: NameDefault, kNamekey , UserIDdefault, kUserIDkey , Passworddefault, kPasswordkey , nil]; self.outlineData = appDefaults; [appDefaults release]; } [window addSubview:rootController.view]; [window makeKeyAndVisible]; NSMutableDictionary *savedLocationDict = [NSMutableDictionary dictionaryWithObject:outlineData forKey:kRestoreLocationKey]; [[NSUserDefaults standardUserDefaults] registerDefaults:savedLocationDict]; [[NSUserDefaults standardUserDefaults] synchronize]; } -(void)applicationWillTerminate:(UIApplication *)application { [[NSUserDefaults standardUserDefaults] setObject:outlineData forKey:kRestoreLocationKey]; } @end Here ViewController is ViewController of Navigation Controller which is attached with one tab bar.. I have attached xib file with ViewController //ViewController.h @interface IBOutlet UITextField *Name; IBOutlet UITextField *UserId; IBOutlet UITextField *Password; } @property(retain,nonatomic) IBOutlet UITextField *Name @property(retain,nonatomic) IBOutlet UITextField *UserId; @property(retain,nonatomic) IBOutlet UITextField *Password; -(IBAction)Save:(id)sender; @end Here in ViewController.m, I am storing object values with keys. /ViewController.m -(IBAction)Save:(id)sender{ TestAppDelegate appDelegate = (TestAppDelegate)[[UIApplication sharedApplication] delegate]; [appDelegate.outlineData setObject:Name.text forKey:kNamekey ]; [appDelegate.outlineData setObject:UserId.text forKey:kUserIDkey ]; [appDelegate.outlineData setObject:Password.text forKey:kPasswordkey]; [[NSUserDefaults standardUserDefaults] synchronize]; } I am accessing stored object using following method. -(void)loadData { TabBarAppDelegate *appDelegate = (TabBarAppDelegate *)[[UIApplication sharedApplication] delegate]; Name = [appDelegate.outlineData objectForKey:kNamekey ]; UserId = [appDelegate.outlineData objectForKey:kUserIDkey ]; Password = [appDelegate.outlineData objectForKey:kPasswordkey]; [Name release]; [UserId release]; [Password release]; } I am getting EXEC_BAD_ACCESS in application. Where I am making mistake ? Thanks,

    Read the article

  • iphone app: delegate not responding

    - by Fiona
    Hi guys.. So i'm very new to this iphone development stuff.... and i'm stuck. I'm building an app that connects to the twitter api. However when the connectionDidFinishLoading method gets called, it doesn't seem to recognise the delegate. Here's the source code of the request class: import "OnePageRequest.h" @implementation OnePageRequest @synthesize username; @synthesize password; @synthesize receivedData; @synthesize delegate; @synthesize callback; @synthesize errorCallBack; @synthesize contactsArray; -(void)friends_timeline:(id)requestDelegate requestSelector:(SEL)requestSelector{ //set the delegate and selector self.delegate = requestDelegate; self.callback = requestSelector; //Set up the URL of the request to send to twitter!! NSURL *url = [NSURL URLWithString:@"http://twitter.com/statuses/friends_timeline.xml"]; [self request:url]; } -(void)request:(NSURL *) url{ theRequest = [[NSMutableURLRequest alloc] initWithURL:url]; theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self]; if (theConnection){ //Create the MSMutableData that will hold the received data. //receivedData is declared as a method instance elsewhere receivedData=[[NSMutableData data] retain]; }else{ //errorMessage.text = @"Error connecting to twitter!!"; } } -(void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge{ if ([challenge previousFailureCount] == 0){ NSLog(@"username: %@ ",[self username]); NSLog(@"password: %@ ",[self password]); NSURLCredential *newCredential = [NSURLCredential credentialWithUser:[self username] password:[self password] persistence:NSURLCredentialPersistenceNone]; [[challenge sender] useCredential:newCredential forAuthenticationChallenge:challenge]; } else { [[challenge sender] cancelAuthenticationChallenge:challenge]; NSLog(@"Invalid Username or password!"); } } -(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{ [receivedData setLength:0]; } -(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{ [receivedData appendData:data]; } -(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{ [theConnection release]; [receivedData release]; [theRequest release]; NSLog(@"Connection failed. Error: %@ %@", [error localizedDescription], [[error userInfo] objectForKey:NSErrorFailingURLStringKey]); if(errorCallBack){ [delegate performSelector:errorCallBack withObject:error]; } } -(void)connectionDidFinishLoading:(NSURLConnection *)connection{ if (delegate && callback){ if([delegate respondsToSelector:[self callback]]){ [delegate performSelector:[self callback] withObject:receivedData]; }else{ NSLog(@"No response from delegate!"); } } [theConnection release]; [theRequest release]; [receivedData release]; } Here's the .h: @interface OnePageRequest : NSObject { NSString *username; NSString *password; NSMutableData *receivedData; NSURLRequest *theRequest; NSURLConnection *theConnection; id delegate; SEL callback; SEL errorCallBack; NSMutableArray *contactsArray; } @property (nonatomic,retain) NSString *username; @property (nonatomic,retain) NSString *password; @property (nonatomic,retain) NSMutableData *receivedData; @property (nonatomic,retain) id delegate; @property (nonatomic) SEL callback; @property (nonatomic) SEL errorCallBack; @property (nonatomic,retain) NSMutableArray *contactsArray; -(void)friends_timeline:(id)requestDelegate requestSelector:(SEL)requestSelector; -(void)request:(NSURL *) url; @end In the method: connectionDidFinishLoading, the following never gets executed: [delegate performSelector:[self callback] withObject:receivedData]; Instead I get the message: "No response from delegate" Anyone see what I'm doing wrong?! or what might be causing the problem? Regards, Fiona

    Read the article

  • copied the reachability-test from apple, but the linker gives a failure

    - by nico
    i have tried to use the reachability-project published by apple to detect a reachability in an own example. i copied the most initialization, but i get this failure in the linker: Ld build/switchViews.build/Debug-iphoneos/test.build/Objects-normal/armv6/test normal armv6 cd /Users/uid04100/Documents/TEST setenv IPHONEOS_DEPLOYMENT_TARGET 3.1.3 setenv PATH "/Developer/Platforms/iPhoneOS.platform/Developer/usr/bin:/Developer/usr/bin:/usr/bin:/bin:/usr/sbin:/sbin" /Developer/Platforms/iPhoneOS.platform/Developer/usr/bin/gcc-4.2 -arch armv6 -isysroot /Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS3.1.3.sdk -L/Users/uid04100/Documents/TEST/build/Debug-iphoneos -F/Users/uid04100/Documents/TEST/build/Debug-iphoneos -filelist /Users/uid04100/Documents/TEST/build/switchViews.build/Debug-iphoneos/test.build/Objects-normal/armv6/test.LinkFileList -dead_strip -miphoneos-version-min=3.1.3 -framework Foundation -framework UIKit -framework CoreGraphics -o /Users/uid04100/Documents/TEST/build/switchViews.build/Debug-iphoneos/test.build/Objects-normal/armv6/test Undefined symbols: "_SCNetworkReachabilitySetCallback", referenced from: -[Reachability startNotifer] in Reachability.o "_SCNetworkReachabilityCreateWithAddress", referenced from: +[Reachability reachabilityWithAddress:] in Reachability.o "_SCNetworkReachabilityScheduleWithRunLoop", referenced from: -[Reachability startNotifer] in Reachability.o "_SCNetworkReachabilityGetFlags", referenced from: -[Reachability connectionRequired] in Reachability.o -[Reachability currentReachabilityStatus] in Reachability.o "_SCNetworkReachabilityUnscheduleFromRunLoop", referenced from: -[Reachability stopNotifer] in Reachability.o "_SCNetworkReachabilityCreateWithName", referenced from: +[Reachability reachabilityWithHostName:] in Reachability.o ld: symbol(s) not found collect2: ld returned 1 exit status my delegate.h: import @class Reachability; @interface testAppDelegate : NSObject { UIWindow *window; UINavigationController *navigationController; Reachability* hostReach; Reachability* internetReach; Reachability* wifiReach; } @property (nonatomic, retain) IBOutlet UIWindow *window; @property (nonatomic, retain) IBOutlet UINavigationController *navigationController; @end my delegate.m: import "testAppDelegate.h" import "SecondViewController.h" import "Reachability.h" @implementation testAppDelegate @synthesize window; @synthesize navigationController; (void) updateInterfaceWithReachability: (Reachability*) curReach { if(curReach == hostReach) { BOOL connectionRequired= [curReach connectionRequired]; if(connectionRequired) { //in these brackets schould be some code with sense, if i´m getting it to run } else { } } if(curReach == internetReach) { } if(curReach == wifiReach) { } } //Called by Reachability whenever status changes. - (void) reachabilityChanged: (NSNotification* )note { Reachability* curReach = [note object]; NSParameterAssert([curReach isKindOfClass: [Reachability class]]); [self updateInterfaceWithReachability: curReach]; } (void)applicationDidFinishLaunching:(UIApplication *)application { // Override point for customization after application launch // Observe the kNetworkReachabilityChangedNotification. When that notification is posted, the // method "reachabilityChanged" will be called. // [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(reachabilityChanged:) name: kReachabilityChangedNotification object: nil]; //Change the host name here to change the server your monitoring hostReach = [[Reachability reachabilityWithHostName: @"www.apple.com"] retain]; [hostReach startNotifer]; [self updateInterfaceWithReachability: hostReach]; internetReach = [[Reachability reachabilityForInternetConnection] retain]; [internetReach startNotifer]; [self updateInterfaceWithReachability: internetReach]; wifiReach = [[Reachability reachabilityForLocalWiFi] retain]; [wifiReach startNotifer]; [self updateInterfaceWithReachability:wifiReach]; [window addSubview:[navigationController view]]; [window makeKeyAndVisible]; } (void)dealloc { [navigationController release]; [window release]; [super dealloc]; } @end

    Read the article

  • Where would I implement this array to pass?

    - by Keeano Martin
    I currently build an NSMutableArray in Class A.m within the ViewDidLoad Method. - (void)viewDidLoad { [super viewDidLoad]; //Question Array Setup and Alloc stratToolsDict = [[NSMutableDictionary alloc] initWithObjectsAndKeys:countButton,@"count",camerButton,@"camera",videoButton,@"video",textButton,@"text",probeButton,@"probe", nil]; stratTools = [[NSMutableArray alloc] initWithObjects:@"Tools",stratToolsDict, nil]; stratObjectsDict = [[NSMutableDictionary alloc]initWithObjectsAndKeys:stratTools,@"Strat1",stratTools,@"Strat2",stratTools,@"Strat3",stratTools,@"Strat4", nil]; stratObjects = [[NSMutableArray alloc]initWithObjects:@"Strategies:",stratObjectsDict,nil]; QuestionDict = [[NSMutableDictionary alloc]initWithObjectsAndKeys:stratObjects,@"Question 1?",stratObjects,@"Question 2?",stratObjects,@"Question 3?",stratObjects,@"Question 4?",stratObjects,@"Question 5?", nil]; //add strategys to questions QuestionsList = [[NSMutableArray alloc]init]; for (int i = 0; i < 1; i++) { [QuestionsList addObject:QuestionDict]; } NSLog(@"Object: %@",QuestionsList); At the end of this method you will see QuestionsList being initialized and now I need to send this Array to Class B. So I place its setters and getters using the @property and @Synthesize method. Class A.h @property (retain, nonatomic) NSMutableDictionary *stratToolsDict; @property (retain, nonatomic) NSMutableArray *stratTools; @property (retain, nonatomic) NSMutableArray *stratObjects; @property (retain, nonatomic) NSMutableDictionary *QuestionDict; @property (retain, nonatomic) NSMutableArray *QuestionsList; Class A.m @synthesize QuestionDict; @synthesize stratToolsDict; @synthesize stratObjects; @synthesize stratTools; @synthesize QuestionsList; I use the property method because I am going to call this variable from Class B and want to be able to assign it to another NSMutableArray. I then add the @property and @class for Class A to Class B.h as well as declare the NSMutableArray in the @interface. #import "Class A.h" @class Class A; @interface Class B : UITableViewController<UITableViewDataSource, UITableViewDelegate>{ NSMutableArray *QuestionList; Class A *arrayQuestions; } @property Class A *arrayQuestions; Then I call NSMutableArray from Class A in the Class B.m -(id)initWithStyle:(UITableViewStyle)style { if ([super initWithStyle:style] != nil) { //Make array arrayQuestions = [[Class A alloc]init]; QuestionList = arrayQuestions.QuestionsList; Right after this I Log the NSMutableArray to view values and check that they are there and it returns NIL. //Log test NSLog(@"QuestionList init method: %@",QuestionList); Info about Class B- Class B is a UIPopOverController for Class A, Class B has one View which holds a UITableView which I have to populate the results of Class A's NSMutableArray. Why is the NsMutableArray coming back as NIL? Ultimately would like some help figuring it out as well, it seems to really have me confused. Help is greatly appreciated!!

    Read the article

  • How can I pass latitude and longitude values from UIViewController to MKMapView?

    - by jerincbus
    I have a detail view that includes three UIButtons, each of which pushes a different view on to the stack. One of the buttons is connected to a MKMapView. When that button is pushed I need to send the latitude and longitude variables from the detail view to the map view. I'm trying to add the string declaration in the IBAction: - (IBAction)goToMapView { MapViewController *mapController = [[MapViewController alloc] initWithNibName:@"MapViewController" bundle:nil]; mapController.mapAddress = self.address; mapController.mapTitle = self.Title; mapController.mapLat = self.lat; mapController.mapLng = self.lng; //Push the new view on the stack [[self navigationController] pushViewController:mapController animated:YES]; [mapController release]; //mapController = nil; } And on my MapViewController.h file I have: #import <UIKit/UIKit.h> #import <MapKit/MapKit.h> #import "DetailViewController.h" #import "CourseAnnotation.h" @class CourseAnnotation; @interface MapViewController : UIViewController <MKMapViewDelegate> { IBOutlet MKMapView *mapView; NSString *mapAddress; NSString *mapTitle; NSNumber *mapLat; NSNumber *mapLng; } @property (nonatomic, retain) IBOutlet MKMapView *mapView; @property (nonatomic, retain) NSString *mapAddress; @property (nonatomic, retain) NSString *mapTitle; @property (nonatomic, retain) NSNumber *mapLat; @property (nonatomic, retain) NSNumber *mapLng; @end And on the pertinent parts of the MapViewController.m file I have: @synthesize mapView, mapAddress, mapTitle, mapLat, mapLng; - (void)viewDidLoad { [super viewDidLoad]; [mapView setMapType:MKMapTypeStandard]; [mapView setZoomEnabled:YES]; [mapView setScrollEnabled:YES]; MKCoordinateRegion region = { {0.0, 0.0 }, { 0.0, 0.0 } }; region.center.latitude = mapLat; //40.105085; region.center.longitude = mapLng; //-83.005237; region.span.longitudeDelta = 0.01f; region.span.latitudeDelta = 0.01f; [mapView setRegion:region animated:YES]; [mapView setDelegate:self]; CourseAnnotation *ann = [[CourseAnnotation alloc] init]; ann.title = mapTitle; ann.subtitle = mapAddress; ann.coordinate = region.center; [mapView addAnnotation:ann]; } But I get this when I try to build: 'error: incompatible types in assignment' for both lat and lng variables. So my questions are am I going about passing the variables from one view to another the right way? And does the MKMapView accept latitude and longitude as a string or a number?

    Read the article

  • NSTimer as a self-targeting ivar.

    - by Matt Wilding
    I have come across an awkward situation where I would like to have a class with an NSTimer instance variable that repeatedly calls a method of the class as long as the class is alive. For illustration purposes, it might look like this: // .h @interface MyClock : NSObject { NSTimer* _myTimer; } - (void)timerTick; @end - // .m @implementation MyClock - (id)init { self = [super init]; if (self) { _myTimer = [[NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(timerTick) userInfo:nil repeats:NO] retain]; } return self; } - (void)dealloc { [_myTimer invalidate]; [_myTImer release]; [super dealloc]; } - (void)timerTick { // Do something fantastic. } @end That's what I want. I don't want to to have to expose an interface on my class to start and stop the internal timer, I just want it to run while the class exists. Seems simple enough. But the problem is that NSTimer retains its target. That means that as long as that timer is active, it is keeping the class from being dealloc'd by normal memory management methods because the timer has retained it. Manually adjusting the retain count is out of the question. This behavior of NSTimer seems like it would make it difficult to ever have a repeating timer as an ivar, because I can't think of a time when an ivar should retain its owning class. This leaves me with the unpleasant duty of coming up with some method of providing an interface on MyClock that allows users of the class to control when the timer is started and stopped. Besides adding unneeded complexity, this is annoying because having one owner of an instance of the class invalidate the timer could step on the toes of another owner who is counting on it to keep running. I could implement my own pseudo-retain-count-system for keeping the timer running but, ...seriously? This is way to much work for such a simple concept. Any solution I can think of feels hacky. I ended up writing a wrapper for NSTimer that behaves exactly like a normal NSTimer, but doesn't retain its target. I don't like it, and I would appreciate any insight.

    Read the article

  • How to create Dictionary object in AppDelegate to access objectkey in another ViewController

    - by TechFusion
    Hello, I have created Window Based application and tab bar controller as root controller. My objective is to store Text Field data values in one tab bar VC and will be accessible and editable by other VC and also retrievable when application start. I am looking to use NSDictionary class in AppDelegate so that I can access stroed Data Values with keys. //TestAppDelegate.h @interface { ..... .... NSDictionary *Data; } @property (nonatomic, retain) NSDictionary *Data; //TestAppDelegate.m #import "TestAppDelegate.h" NSString *kNamekey =@"Namekey"; NSString *kUserIDkey =@"UserIDkey"; NSString *kPasswordkey =@"Passwordkey"; @implemetation TestAppDelegate @synthesize Data; -(void)applicationDidFinishLaunching:(UIApplication)application { NSString *NameDefault; NSString *UserIDdefault; NSString *Passworddefault; NSString *testvalue = [[NSUserDefaults standardUserDefaults] stringForKey: kNamekey]; if(testvalue == nil) { NSDictionary *appDefaults = [NSDictionary dictionaryWithObjectsAndKeys: NameDefault, kNamekey, UserIdefault kUserIDkey, Passwordefault kPasswordkey, nil]; self.Data = appDefaults; [[NSUserDefaults standardUserDefaults] registerDefaults:appDefaults]; [[NSUserDefaults standardUserDefaults] synchronize]; } else { } } Here ViewController is ViewController of Navigation Controller which is attached with one tab bar.. I have attached xib file with ViewController //ViewController.h @interface IBOutlet UITextField *Name; IBOutlet UITextField *UserId; IBOutlet UITextField *Password; } @property(retain,nonatomic) IBOutlet UITextField *Name @property(retain,nonatomic) IBOutlet UITextField *UserId; @property(retain,nonatomic) IBOutlet UITextField *Password; -(IBAction)Save:(id)sender; @end Here in ViewController.m I want to store Text Field input data with key which are defined in AppDelegate. I have linked Save Barbutton with action. Here I am not getting how to access NSDictionary class with object and keys in ViewController. //ViewController.m -(IBAction)Save:(id)sender{ TestAppDelegate *appDelegate = (TestAppDelegate*)[[UIApplication sharedApplication] delegate]; //Here how to access knamekey here to set object(Name.test) value with key } Please guide me about this. Thanks,

    Read the article

  • How to release a "PopUp" view"?

    - by david
    I have this class that shows a popup. I do a alloc-init on it and it comes up. DarkVader* darkPopUp = [[DarkVader alloc] init:theButton helpMessage:[theButton.titleLabel.text intValue] isADay:NO offset:0]; It shows itself and if the user presses Ok it disappears. When do I release this? I could do a [self release] in the class when the OK button is pressed. Is this correct? If I do this the Analyzer says it has a retain count of +1 and gets leaked in the calling function. If I release it just after the alloc-init the Analyzer says it has a retain count of +0 and i should not release it. DLog(@"DarkVader retain count: %i", [darkPopUp retainCount]); says it has a retain count of 2. I'm confused. In short my question is: How do I release an object that gets initialized does some work and ends but no one is there to release it in the calling function.

    Read the article

  • Storing high precision latitude/longitude numbers in iOS Core Data

    - by Bryan
    I'm trying to store Latitude/Longitudes in core data. These end up being anywhere from 6-20 digit precision. And for whatever reason, i had them as floats in Core Data, its rounding them and not giving me the exact values back. I tried "decimal" type, with no luck either. Are NSStrings my only other option? EDIT NSManagedObject: @interface Event : NSManagedObject { } @property (nonatomic, retain) NSDecimalNumber * dec; @property (nonatomic, retain) NSDate * timeStamp; @property (nonatomic, retain) NSNumber * flo; @property (nonatomic, retain) NSNumber * doub; Here's the code for a sample number that I store into core data: NSNumber *n = [NSDecimalNumber decimalNumberWithString:@"-97.12345678901234567890123456789"]; Code to access it again: NSNumber *n = [managedObject valueForKey:@"dec"]; NSNumber *f = [managedObject valueForKey:@"flo"]; NSNumber *d = [managedObject valueForKey:@"doub"]; Printed values: Printing description of n: -97.1234567890124 Printing description of f: <CFNumber 0x603f250 [0xfef3e0]>{value = -97.12345678901235146441, type = kCFNumberFloat64Type} Printing description of d: <CFNumber 0x6040310 [0xfef3e0]>{value = -97.12345678901235146441, type = kCFNumberFloat64Type}

    Read the article

  • How to get the title and subtitle for a pin when we are implementing the MKAnnotation?

    - by wolverine
    I have implemented the MKAnnotation as below. I will put a lot of pins and the information for each of those pins are stored in an array. Each member of this array is an object whose properties will give the values for the title and subtitle of the pin. Each object corresponds to a pin. But how can I display these values for the pin when I click a pin?? @interface UserAnnotation : NSObject <MKAnnotation> { CLLocationCoordinate2D coordinate; NSString *title; NSString *subtitle; NSString *city; NSString *province; } @property (nonatomic, assign) CLLocationCoordinate2D coordinate; @property (nonatomic, retain) NSString *title; @property (nonatomic, retain) NSString *subtitle; @property (nonatomic, retain) NSString *city; @property (nonatomic, retain) NSString *province; -(id)initWithCoordinate:(CLLocationCoordinate2D)c; And .m is @implementation UserAnnotation @synthesize coordinate, title, subtitle, city, province; - (NSString *)title { return title; } - (NSString *)subtitle { return subtitle; } - (NSString *)city { return city; } - (NSString *)province { return province; } -(id)initWithCoordinate:(CLLocationCoordinate2D)c { coordinate=c; NSLog(@"%f,%f",c.latitude,c.longitude); return self; } @end

    Read the article

  • Display subclass data in XCode Expression window

    - by Nick VanderPyle
    I'm debugging an iPhone application I've written using XCode 3.2 and I cannot view the relevant public properties of an object I pull from Core Data. When I watch the object in the Expressions window it only displays the data from the base NSManagedObject. I'd like to see the properties that are on the subclass, not the superclass. If it helps, here's some of the code I'm using. Settings is a subclass of NSManagedObject. I created it using XCode's built-in modeler. Declared like: @interface Settings : NSManagedObject { } @property (nonatomic, retain) NSNumber * hasNews; @property (nonatomic, retain) NSString * logoUrl; @property (nonatomic, retain) NSNumber * hasPaymentGateway; @property (nonatomic, retain) NSString * customerCode; ... In the interface of my controller I have: Settings *settings; I populate settings with: settings = (Settings *)[NSEntityDescription insertNewObjectForEntityForName:@"Settings" inManagedObjectContext:UIAppManagedObjectContext()]; I then set the properties like: settings.hasNews = [NSNumber numberWithBool:TRUE]; I've tried casting settings as (Settings *) in the Expression window but that doesn't help. All I see are the properties to NSManagedObject. I'm using NSLog but would rather not.

    Read the article

  • Passing NULL value

    - by FFXIII
    Hi. I use an instance of NSXMLParser. I store found chars in NSMutableStrings that are stored in an NSMutableDictionary and these Dicts are then added to an NSMutableArray. When I test this everything seems normal: I count 1 array, x dictionnaries and x strings. In a detailview controller file I want to show my parsed results. I call the class where everthing is stored but I get (null) returned. This is what I do (wrong): XMLParser.h @interface XMLParser : NSObject { NSMutableArray *array; NSMUtableDictionary *dictionary; NSSMutabletring *element; } @property (nonatomic, retain) NSMutableArray *array; @property (nonatomic, retain) NSMutableDictionary *dictionary; @property (nonatomic, retain) NSMutableString *element; XMLParser.m @synthesize array, dictionary, element; //parsing goes on here & works fine //so 'element' is filled with content and stored in a dict in an array //and released at the end of the file In my controller file I do this: controller.h @class XMLParser; @interface controller : UIViewController { XMLParser *aXMLParser; } @property (nonatomic, retain) XMLParser *aXMLParser; controller.m #import "XMLParser.h" @synthesize aXMLParser; - (void)viewDidLoad { NSLog(@"test array: %@", aXMLParser.array); NSLog(@"test dict: %@", aXMLParser.dictionary); NSLog(@"test element: %@", aXMLParser.element); } When I test the value of my array, a dict or an element in the XMLParser.h file I get my result. What am I doing wrong so I can't call my results in my controller file? Any help is welcome, because I'm pretty stuck right now :/

    Read the article

  • App Crashes Loading View Controllers

    - by golfromeo
    I have the following code in my AppDelegate.h file: @class mainViewController; @class AboutViewController; @interface iSearchAppDelegate : NSObject <UIApplicationDelegate> { UIWindow *window; mainViewController *viewController; AboutViewController *aboutController; UINavigationController *nav; } @property (nonatomic, retain) IBOutlet UIWindow *window; @property (nonatomic, retain) IBOutlet mainViewController *viewController; @property (nonatomic, retain) IBOutlet AboutViewController *aboutController; @property (nonatomic, retain) IBOutlet UINavigationController *nav; [...IBActions declared here...] @end Then, in my .m file: @implementation iSearchAppDelegate @synthesize window; @synthesize viewController, aboutController, settingsData, nav, engines; (void)applicationDidFinishLaunching:(UIApplication *)application { [window addSubview:nav.view]; [window addSubview:aboutController.view]; [window addSubview:viewController.view]; [window makeKeyAndVisible]; } -(IBAction)switchToHome{ [window bringSubviewToFront:viewController.view]; } -(IBAction)switchToSettings{ [window bringSubviewToFront:nav.view]; } -(IBAction)switchToAbout{ [window bringSubviewToFront:aboutController.view]; } - (void)dealloc { [viewController release]; [aboutController release]; [nav release]; [window release]; [super dealloc]; } @end Somehow, when I run the app, the main view presents itself fine... however, when I try to execute the actions to switch views, the app crashes with an EXC_BAD_ACCESS. Thanks for any help in advance.

    Read the article

  • Cocoa memory management - object going nil on me

    - by SirRatty
    Hi all, Mac OS X 10.6, Cocoa project, with retain/release gc I've got a function which: iterates over a specific directory, scans it for subfolders (included nested ones), builds an NSMutableArray of strings (one string per found subfolder path), and returns that array. e.g. (error handling removed for brevity). NSMutableArray * ListAllSubFoldersForFolderPath(NSString *folderPath) { NSMutableArray *a = [NSMutableArray arrayWithCapacity:100]; NSString *itemName = nil; NSFileManager *fm = [NSFileManager defaultManager]; NSDirectoryEnumerator *e = [fm enumeratorAtPath:folderPath]; while (itemName = [e nextObject]) { NSString *fullPath = [folderPath stringByAppendingPathComponent:itemName]; BOOL isDirectory; if ([fm fileExistsAtPath:fullPath isDirectory:&isDirectory]) { if (isDirectory is_eq YES) { [a addObject: fullPath]; } } } return a; } The calling function takes the array just once per session, keeps it around for later processing: static NSMutableArray *gFolderPaths = nil; ... gFolderPaths = ListAllSubFoldersForFolderPath(myPath); [gFolderPaths retain]; All appears good at this stage. [gFolderPaths count] returns the correct number of paths found, and [gFolderPaths description] prints out all the correct path names. The problem: When I go to use gFolderPaths later (say, the next run through my event loop) my assertion code (and gdb in Xcode) tells me that it is nil. I am not modifying gFolderPaths in any way after that initial grab, so I am presuming that my memory management is screwed and that gFolderPaths is being released by the runtime. My assumptions/presumptions I do not have to retain each string as I add it to the mutable array because that is done automatically, but I do have to retain the the array once it is handed over to me from the function, because I won't be using it immediately. Is this correct? Any help is appreciated.

    Read the article

  • Most Efficient way to deal with multiple CCSprites?

    - by nardsurfer
    I have four different types of objects within my environment(box2d), each type of object having multiple instances of itself, and would like to find the most efficient way to deal with adding and manipulating all the CCSprites. The sprites are all from different files, so would it be best to create each sprite and add it to a data structure (NSMutableArray) or would I use a CCSpriteBatchNode even though each CCSprite file is different (for each type of object)? Thanks. @interface LevelScene : CCLayer { b2World* world; GLESDebugDraw *m_debugDraw; CCSpriteBatchNode *ballBatch; CCSpriteBatchNode *blockBatch; CCSpriteBatchNode *springBatch; CCSprite *goal; } +(id) scene; // adds a new sprite at a given coordinate -(void) addNewBallWithCoords:(CGPoint)p; // loads the objects (blocks, springs, and the goal), returns the Level Object -(Level) loadLevel:(int)level; @end or using NSMutableArray objects within the Level object... @interface zLevel : zThing { NSMutableArray *springs; NSMutableArray *blocks; NSMutableArray *balls; zGoal *goal; int levelNumber; } @property(nonatomic,retain)NSMutableArray *springs; @property(nonatomic,retain)NSMutableArray *blocks; @property(nonatomic,retain)NSMutableArray *balls; @property(nonatomic,retain)zGoal *goal; @property(nonatomic,assign)int levelNumber; -(void)initWithLevel:(int)level; -(void)loadLevelThings; @end

    Read the article

  • Upgrade only one version of XP to Windows 8 on a dual boot computer

    - by Shane
    I have a computer running Windows XP Pro 32-bit and 64-bit in dual boot. I need to retain Windows XP 32-bit Pro, as I have expensive software that will only run on that specific version. I want to upgrade my 64-bit installation of XP to Windows 8 without losing the 32-bit installation. If I simply use the ISO to upgrade from within my XP 64-bit installation, will I retain dual boot for both XP 32-bit and Windows 8?

    Read the article

  • Iphone SDK - adding UITableView to UIView

    - by Shashi
    Hi, I am trying to learn how to use different views, for this sample test app, i have a login page, upon successful logon, the user is redirected to a table view and then upon selection of an item in the table view, the user is directed to a third page showing details of the item. the first page works just fine, but the problem occurs when i go to the second page, the table shown doesn't have title and i cannot add title or toolbar or anything other than the content of the tables themselves. and when i click on the item, needless to say nothing happens. no errors as well. i am fairly new to programming and have always worked on Java but never on C(although i have some basic knowledge of C) and Objective C is new to me. Here is the code. import @interface NavigationTestAppDelegate : NSObject { UIWindow *window; UIViewController *viewController; IBOutlet UITextField *username; IBOutlet UITextField *password; IBOutlet UILabel *loginError; //UINavigationController *navigationController; } @property (nonatomic, retain) IBOutlet UIViewController *viewController; @property (nonatomic, retain) IBOutlet UIWindow *window; @property (nonatomic, retain) IBOutlet UITextField *username; @property (nonatomic, retain) IBOutlet UITextField *password; @property (nonatomic, retain) IBOutlet UILabel *loginError; -(IBAction) login; -(IBAction) hideKeyboard: (id) sender; @end import "NavigationTestAppDelegate.h" import "RootViewController.h" @implementation NavigationTestAppDelegate @synthesize window; @synthesize viewController; @synthesize username; @synthesize password; @synthesize loginError; pragma mark - pragma mark Application lifecycle -(IBAction) hideKeyboard: (id) sender{ [sender resignFirstResponder]; } (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { // Override point for customization after app launch //RootViewController *rootViewController = [[RootViewController alloc] init]; //[window addSubview:[navigationController view]]; [window addSubview:[viewController view]]; [window makeKeyAndVisible]; return YES; } -(IBAction) login { RootViewController *rootViewController = [[RootViewController alloc] init]; //NSString *user = [[NSString alloc] username. if([username.text isEqualToString:@"test"]&&[password.text isEqualToString:@"test"]){ [window addSubview:[rootViewController view]]; //[window addSubview:[navigationController view]]; [window makeKeyAndVisible]; //rootViewController.awakeFromNib; } else { loginError.text = @"LOGIN ERROR"; [window addSubview:[viewController view]]; [window makeKeyAndVisible]; } } (void)applicationWillTerminate:(UIApplication *)application { // Save data if appropriate } pragma mark - pragma mark Memory management (void)dealloc { //[navigationController release]; [viewController release]; [window release]; [super dealloc]; } @end import @interface RootViewController : UITableViewController { IBOutlet NSMutableArray *views; } @property (nonatomic, retain) IBOutlet NSMutableArray * views; @end // // RootViewController.m // NavigationTest // // Created by guest on 4/23/10. // Copyright MyCompanyName 2010. All rights reserved. // import "RootViewController.h" import "OpportunityOne.h" @implementation RootViewController @synthesize views; //@synthesize navigationViewController; pragma mark - pragma mark View lifecycle (void)viewDidLoad { views = [ [NSMutableArray alloc] init]; OpportunityOne *opportunityOneController; for (int i=1; i<=20; i++) { opportunityOneController = [[OpportunityOne alloc] init]; opportunityOneController.title = [[NSString alloc] initWithFormat:@"Opportunity %i",i]; [views addObject:[NSDictionary dictionaryWithObjectsAndKeys: [[NSString alloc] initWithFormat:@"Opportunity %i",i], @ "title", opportunityOneController, @"controller", nil]]; self.title=@"GPS"; } /*UIBarButtonItem *temporaryBarButtonItem = [[UIBarButtonItem alloc] init]; temporaryBarButtonItem.title = @"Back"; self.navigationItem.backBarButtonItem = temporaryBarButtonItem; [temporaryBarButtonItem release]; */ //self.title =@"Global Platform for Sales"; [super viewDidLoad]; //[temporaryBarButtonItem release]; //[opportunityOneController release]; // 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 // Customize the number of sections in the table view. - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { return 1; } // Customize the number of rows in the table view. - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return [views count]; } // Customize the appearance of table view cells. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *CellIdentifier = @"Cell"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if (cell == nil) { cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease]; } // Configure the cell. cell.textLabel.text = [[views objectAtIndex:indexPath.row] objectForKey:@"title"]; return cell; } pragma mark - pragma mark Table view delegate (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { //UIViewController *targetViewController = [[views objectAtIndex:indexPath.row] objectForKey:@"controller"]; UIViewController *targetViewController = [[views objectAtIndex:indexPath.row] objectForKey:@"controller"]; [[self navigationController] pushViewController:targetViewController 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; } (void)dealloc { [views release]; [super dealloc]; } @end Wow, i was finding it real hard to post the code. i apologize for the bad formatting, but i just couldn't get past the formatting rules for this text editor. Thanks, Shashi

    Read the article

  • Xcode is not calling asp.net webservice

    - by vaibhav
    I have oracle database and using webservice i want to insert some records in to it So i created webservice in asp.net as follows public bool PickPill(string Me_id, string Mem_device_id, string Test_datetime, string Creation_id, string PillBayNo) { string Hed_seq_id = Hed_seq_Id(); bool ResultHED = InsHealthEData(Hed_seq_id, Mem_device_id, Me_id, Test_datetime, Creation_id); bool ResultHET = InsHealthETest(Hed_seq_id, PillBayNo, Test_datetime, Creation_id); if (ResultHED == ResultHET == true) return true; else return false; } this function did all data insertion trick for me i tested this service on the local mechine with ip address http:72.44.151.178/PickPillService.asmx then, I see an example on how to attach asp.net web service to iphone apps http://www.devx.com/wireless/Article/43209/0/page/4 then i created simillar code in xcode which has 2 files ConsumePillServiceViewController.m ConsumePillServiceViewController.h file Now, Using Designer of xcode i created 5 textboxes(Me_id,Mem_device_id,Test_datetime,Creation_id,PillBayNo) with all parameters hardcode as our service demands then modify my ConsumePillServiceViewController.h file as follows @interface ConsumePillServiceViewController : UIViewController { //---outlets--- IBOutlet UITextField *Me_id; IBOutlet UITextField *Mem_device_id; IBOutlet UITextField *Test_datetime; IBOutlet UITextField *Creation_id; IBOutlet UITextField *PillBayNo; //---web service access--- NSMutableData *webData; NSMutableString *soapResults; NSURLConnection *conn; } @property (nonatomic, retain) UITextField *Me_id; @property (nonatomic, retain) UITextField *Mem_device_id; @property (nonatomic, retain) UITextField *Test_datetime; @property (nonatomic, retain) UITextField *Creation_id; @property (nonatomic, retain) UITextField *PillBayNo; - (IBAction)buttonClicked:(id)sender; @end and ConsumePillServiceViewController.m as follows import "ConsumePillServiceViewController.h" @implementation ConsumePillServiceViewController @synthesize Me_id; @synthesize Mem_device_id; @synthesize Test_datetime; @synthesize Creation_id; @synthesize PillBayNo; (IBAction)buttonClicked:(id)sender { NSString *soapMsg = @"" "" "" ""; NSString *smMe_id= [soapMsg stringByAppendingString: [NSString stringWithFormat: @"%@",Me_id.text]]; NSString *smMem_device_id= [smMe_id stringByAppendingString: [NSString stringWithFormat: @"%@",Mem_device_id.text]]; NSString *smTest_datetime= [smMem_device_id stringByAppendingString: [NSString stringWithFormat: @"%@",Test_datetime.text]]; NSString *smCreation_id= [smTest_datetime stringByAppendingString: [NSString stringWithFormat: @"%@",Creation_id.text]]; NSString *smPillBayNo= [smCreation_id stringByAppendingString: [NSString stringWithFormat: @"%@",PillBayNo.text]]; NSString *smRestMsg= [smPillBayNo stringByAppendingString: @"" "" ""]; soapMsg=smRestMsg; //---print it to the Debugger Console for verification--- NSLog(soapMsg); NSURL *url = [NSURL URLWithString: //create a URL load request object using instances : @"http://72.44.151.178/PickPillService.asmx"];//of the NSMutableURLRequest and NSURL objects NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url]; //opulate the request object with the various headers, such as Content-Type, SOAPAction, and Content-Length. //You also set the HTTP method and HTTP body NSString *msgLength = [NSString stringWithFormat:@"%d", [soapMsg length]]; [req addValue:@"text/xml; charset=utf-8" forHTTPHeaderField:@"Content-Type"]; [req addValue:@"http://tempuri.org/PickPill" forHTTPHeaderField:@"SOAPAction"]; [req addValue:msgLength forHTTPHeaderField:@"Content-Length"]; //---set the HTTP method and body--- [req setHTTPMethod:@"POST"]; [req setHTTPBody: [soapMsg dataUsingEncoding:NSUTF8StringEncoding]]; conn = [[NSURLConnection alloc] initWithRequest:req delegate:self]; //establish the connection with the web service, if (conn) { //you use the NSURLConnection class together with the request object just created webData = [[NSMutableData data] retain];//webData object use to receive incoming data from the web service } }//End of button clicked event -(void) connection:(NSURLConnection *) connection //Recive response didReceiveResponse:(NSURLResponse *) response { [webData setLength: 0]; } -(void) connection:(NSURLConnection *) connection //Repeative call method and append data to webData didReceiveData:(NSData *) data { [webData appendData:data]; } -(void) connection:(NSURLConnection *) connection//If error occure error should be displayed didFailWithError:(NSError *) error { [webData release]; [connection release]; } -(void) connectionDidFinishLoading:(NSURLConnection *) connection { NSLog(@"DONE. Received Bytes: %d", [webData length]); NSString *theXML = [[NSString alloc] initWithBytes: [webData mutableBytes] length:[webData length] encoding:NSUTF8StringEncoding]; //---shows the XML--- NSLog(theXML); [connection release]; [webData release]; } (void)didReceiveMemoryWarning { // Releases the view if it doesn't have a superview. [super didReceiveMemoryWarning]; // Release any cached data, images, etc that aren't in use. } (void)viewDidUnload { // Release any retained subviews of the main view. // e.g. self.myOutlet = nil; } (void)dealloc { [Me_id release]; [Creation_id release]; [Mem_device_id release]; [Test_datetime release]; [PillBayNo release]; [soapResults release]; [super dealloc]; } @end I did all things as shown in the website and when i built application it successfully built but in the debuggin window i see (gdb) continue 2010-03-17 09:09:54.595 ConsumePillService[6546:20b] A00000004303101103/13/2010 07:34:38Hboxdata2 (gdb) continue (gdb) continue (gdb) continue 2010-03-17 09:10:05.411 ConsumePillService[6546:20b] DONE. Received Bytes: 476 2010-03-17 09:10:05.412 ConsumePillService[6546:20b] soap:ServerServer was unable to process request. ---> One or more errors occurred during processing of command. ORA-00936: missing expression It should return me true if all things are ok What is this ORA-00936 error all about as it is not releted with webservice Please help me solving this problem Thanks in advance, Vaibhav Deshpande

    Read the article

  • Returning objects with autorelease but I still leak memory

    - by gok
    I am leaking memory on this: my custom class: + (id)vectorWithX:(float)dimx Y:(float)dimy{ return [[[Vector alloc] initVectorWithX:dimx Y:dimy] autorelease]; } - (Vector*)add:(Vector*)q { return [[[Vector vectorWithX:x+q.x Y:y+q.y] retain] autorelease]; } in app delegate I initiate it: Vector *v1 = [[Vector alloc] initVector]; Vector *v2 = [[Vector alloc] initVector]; Vector *vtotal = [[v1 add:v2] retain]; [v1 release]; [v2 release]; [vtotal release]; How this leaks? I release or autorelease them properly. The app crashes immediately if I don't retain these, because of an early release I guess. It also crashes if I add another release.

    Read the article

  • How do I set an Array in one class with another array in another class in Objective-C

    - by Stef
    Hi Guys, I've populated and array with data like this in one class... PowerClass .h NSMutableArray pickerArray; @property (nonatomic, retain) NSMutableArray pickerArray; - PowerClass .m @synthesize pickerArray; @implementation NSMutableArray *array = [[NSArray alloc] initWithObjects:@"stef", @"steve", @"baddamans", @"jonny", nil]; pickerArray = [NSMutableArray arrayWithArray:array]; And I'm trying to set the Array in another class WeekClass .h PowerClass *powerClass; NSMutableArray *pickerData; @property (nonatomic, retain) NSMutableArray pickerData; @property (nonatomic, retain) PowerClass *powerClass; WeekClass .m @implementation pickerData = [NSMutableArray arrayWithArray:powerClass.pickerArray]; I have no errors or warnings. It just crashes. The NSLog says that the powerClass.PickerArray is Null... I don't know why this is... Please help point me in the right direction... Thanx guys Stef :-)

    Read the article

  • How do I set an array in one class with another array in another class

    - by Stef
    I've populated and array with data like this in one class... PowerClass.h NSMutableArray pickerArray; @property (nonatomic, retain) NSMutableArray pickerArray; - PowerClass.m @synthesize pickerArray; @implementation NSMutableArray *array = [[NSArray alloc] initWithObjects:@"stef", @"steve", @"baddamans", @"jonny", nil]; pickerArray = [NSMutableArray arrayWithArray:array]; And I'm trying to set the Array in another class WeekClass.h PowerClass *powerClass; NSMutableArray *pickerData; @property (nonatomic, retain) NSMutableArray pickerData; @property (nonatomic, retain) PowerClass *powerClass; WeekClass.m @implementation pickerData = [NSMutableArray arrayWithArray:powerClass.pickerArray]; I have no errors or warnings. It just crashes. The NSLog says that the powerClass.pickerArray is NULL. Please help point me in the right direction.

    Read the article

  • NSManagedObject - NSSet gets removed ??

    - by aryaxt
    I have an nsmanagedObject this NSManagedObject contains an NSSet. the data for NSSet get's lost when i call release on an NSManagedObject with retain count of 2. Wouldn't retaining an NSManagedObject also retain all it's properties?? - (id)initViewWithManagedObject :(NSManagedObject)obj { if (self = [super init]) { self.managedObject = obj; } } - (void)dealloc { [self.managedObject release]; //Here is when the nsset data gets removed [super dealloc]; } Below describes how the property was created @interface MyManagedObject :NSManagedObject @property (nonatomic, retain) NSSet *mySet; @end @implementation MyManagedObject @dynamic mySet; @end

    Read the article

  • NSDate & Memory management

    - by iFloh
    Hi, memory management still gives me grief. This time it is an NSDate iVar that I init using NSDate *myNSDate = [[NSDate date] firstDayOfMonth]; with a method call to - (NSDate *)firstDayOfMonth { NSDateComponents *tmpDateComponents = [[NSCalendar currentCalendar] components:NSYearCalendarUnit | NSMonthCalendarUnit | NSEraCalendarUnit | NSWeekCalendarUnit | NSWeekdayOrdinalCalendarUnit fromDate:self]; [tmpDateComponents setDay:1]; [tmpDateComponents setHour:0]; [tmpDateComponents setMinute:0]; [tmpDateComponents setSecond:0]; return [[NSCalendar currentCalendar] dateFromComponents:tmpDateComponents]; } At the end of the init call the retain count is at 1 (Note the iVar is not defined as a property). When I step into the viewWillAppear method the myNSDate has vanished. I tried to do an explicit retain on it, but that only lasts until I update the iVar using the above method again. I though - ok - I add the retain to the return of the function, but that makes the leak analyser throw up an error. What am I doing wrong?

    Read the article

  • How to refactor my design, if it seems to require multiple inheritance?

    - by Omega
    Recently I made a question about Java classes implementing methods from two sources (kinda like multiple inheritance). However, it was pointed out that this sort of need may be a sign of a design flaw. Hence, it is probably better to address my current design rather than trying to simulate multiple inheritance. Before tackling the actual problem, some background info about a particular mechanic in this framework: It is a simple game development framework. Several components allocate some memory (like pixel data), and it is necessary to get rid of it as soon as you don't need it. Sprites are an example of this. Anyway, I decided to implement something ala Manual-Reference-Counting from Objective-C. Certain classes, like Sprites, contain an internal counter, which is increased when you call retain(), and decreased on release(). Thus the Resource abstract class was created. Any subclass of this will obtain the retain() and release() implementations for free. When its count hits 0 (nobody is using this class), it will call the destroy() method. The subclass needs only to implement destroy(). This is because I don't want to rely on the Garbage Collector to get rid of unused pixel data. Game objects are all subclasses of the Node class - which is the main construction block, as it provides info such as position, size, rotation, etc. See, two classes are used often in my game. Sprites and Labels. Ah... but wait. Sprites contain pixel data, remember? And as such, they need to extend Resource. But this, of course, can't be done. Sprites ARE nodes, hence they must subclass Node. But heck, they are resources too. Why not making Resource an interface? Because I'd have to re-implement retain() and release(). I am avoiding this in virtue of not writing the same code over and over (remember that there are multiple classes that need this memory-management system). Why not composition? Because I'd still have to implement methods in Sprite (and similar classes) that essentially call the methods of Resource. I'd still be writing the same code over and over! What is your advice in this situation, then?

    Read the article

  • Problem releasing UIImageView after adding to UIScrollView

    - by Josiah Jordan
    I'm having a memory problem related to UIImageView. After adding this view to my UIScrollView, if I try to release the UIImageView the application crashes. According to the stack trace, something is calling [UIImageView stopAnimating] after [UIImageView dealloc] is called. However, if I don't release the view the memory is never freed up, and I've confirmed that there remains an extra retain call on the view after deallocating...which causes my total allocations to climb quickly and eventually crash the app after loading the view multiple times. I'm not sure what I'm doing wrong here though...I don't know what is trying to access the UIImageView after it has been released. I've included the relevant header and implementation code below (I'm using the Three20 framework, if that has anything to do with it...also, AppScrollView is just a UIScrollView that forwards the touchesEnded event to the next responder): Header: @interface PhotoHiResPreviewController : TTViewController <UIScrollViewDelegate> { NSString* imageURL; UIImage* hiResImage; UIImageView* imageView; UIView* mainView; AppScrollView* mainScrollView; } @property (nonatomic, retain) NSString* imageURL; @property (nonatomic, retain) NSString* imageShortURL; @property (nonatomic, retain) UIImage* hiResImage; @property (nonatomic, retain) UIImageView* imageView; - (id)initWithImageURL:(NSString*)imageTTURL; Implementation: @implementation PhotoHiResPreviewController @synthesize imageURL, hiResImage, imageView; - (id)initWithImageURL:(NSString*)imageTTURL { if (self = [super init]) { hiResImage = nil; NSString *documentsDirectory = [NSString stringWithString:[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject]]; [self setImageURL:[NSString stringWithFormat:@"%@/%@.jpg", documentsDirectory, imageTTURL]]; } return self; } - (void)loadView { [super loadView]; // Initialize the scroll view hiResImage = [UIImage imageWithContentsOfFile:self.imageURL]; CGSize photoSize = [hiResImage size]; mainScrollView = [[AppScrollView alloc] initWithFrame:[UIScreen mainScreen].bounds]; mainScrollView.autoresizingMask = ( UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight); mainScrollView.backgroundColor = [UIColor blackColor]; mainScrollView.contentSize = photoSize; mainScrollView.contentMode = UIViewContentModeScaleAspectFit; mainScrollView.delegate = self; // Create the image view and add it to the scrollview. UIImageView *tempImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0.0, 0.0, photoSize.width, photoSize.height)]; tempImageView.contentMode = UIViewContentModeCenter; [tempImageView setImage:hiResImage]; self.imageView = tempImageView; [tempImageView release]; [mainScrollView addSubview:imageView]; // Configure zooming. CGSize screenSize = [[UIScreen mainScreen] bounds].size; CGFloat widthRatio = screenSize.width / photoSize.width; CGFloat heightRatio = screenSize.height / photoSize.height; CGFloat initialZoom = (widthRatio > heightRatio) ? heightRatio : widthRatio; mainScrollView.maximumZoomScale = 3.0; mainScrollView.minimumZoomScale = initialZoom; mainScrollView.zoomScale = initialZoom; mainScrollView.bouncesZoom = YES; mainView = [[UIView alloc] initWithFrame:[UIScreen mainScreen].bounds]; mainView.autoresizingMask = ( UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight); mainView.backgroundColor = [UIColor blackColor]; mainView.contentMode = UIViewContentModeScaleAspectFit; [mainView addSubview:mainScrollView]; // Add to view self.view = mainView; [imageView release]; [mainScrollView release]; [mainView release]; } - (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView { return imageView; } - (void)dealloc { mainScrollView.delegate = nil; TT_RELEASE_SAFELY(imageURL); TT_RELEASE_SAFELY(hiResImage); [super dealloc]; } I'm not sure how to get around this. If I remove the call to [imageView release] at the end of the loadView method everything works fine...but I have massive allocations that quickly climb to a breaking point. If I DO release it, however, there's that [UIImageView stopAnimating] call that crashes the application after the view is deallocated. Thanks for any help! I've been banging my head against this one for days. :-P Cheers, Josiah

    Read the article

< Previous Page | 4 5 6 7 8 9 10 11 12 13 14 15  | Next Page >