IOS Why does Initialisation fail with _variable but not with self.variable for NSNumber? - iphone

I have the following Class:
---- .h file
#import <Foundation/Foundation.h>
#import "MapperProtocoll.h"
#interface ServiceRequest : NSObject {
}
#property (strong, nonatomic) NSString *url;
#property (strong, nonatomic) NSString *postData;
#property (strong, nonatomic) NSNumber *requestId;
#property (strong, nonatomic) id<ServiceMapperDelegate> mapper;
-(id)initWithUrl:(NSString *)url andWithPostdata:(NSString *)postData;
#end
------- .m file
#import "ServiceRequest.h"
#implementation ServiceRequest
#synthesize url = _url, postData = _postData, requestId = _requestId, mapper = _mapper;
-(id)initWithUrl:(NSString *)url andWithPostdata:(NSString *)postData {
if (self = [super init]) {
_url = url;
_postData = postData;
self.requestId = [NSNumber numberWithInt:-1]; // HERE IS THE PROBLEM
}
return self;
}
#end
Why does
self.requestId = [NSNumber numberWithInt:-1];
work but
_requestId = [NSNumber numberWithInt:-1];
throw a runtime error?

The class method [NSNumber numberWithInt:-1] is returning an autoreleased value. When you use the synthesized setter method, the value gets retained by the setter. When you bypass the setter, there is no retain... So as soon as the autorelease pool is drained you have a dangling pointer.

Related

Singleton changes is not preserved to the next view IOS

I have a singleton class which I intend to share throughout my whole application.
It looks like this:
.m
#implementation PersonalGlobal
#synthesize firstName;
#synthesize lastName;
#synthesize SSN;
#synthesize customerNo;
#synthesize email;
#synthesize address;
#synthesize city;
#synthesize postalCode;
#synthesize telNo;
#synthesize mobileNo;
#pragma mark Singleton Methods
+ (id)sharedPersonal {
static PersonalGlobal *sharedPersonalGlobal = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sharedPersonalGlobal = [[self alloc] init];
});
return sharedPersonalGlobal;
}
- (void)dealloc {
[super dealloc];
// Should never be called
}
#end
.h
#import <foundation/Foundation.h>
#interface PersonalGlobal : NSObject {
NSString *firstName;
NSString *lastName;
NSString *SSN;
NSString *customerNo;
NSString *email;
NSString *address;
NSString *city;
NSString *postalCode;
NSString *telNo;
NSString *mobileNo;
}
#property (nonatomic, retain) NSString *firstName;
#property (nonatomic, retain) NSString *lastName;
#property (nonatomic, retain) NSString *SSN;
#property (nonatomic, retain) NSString *customerNo;
#property (nonatomic, retain) NSString *email;
#property (nonatomic, retain) NSString *address;
#property (nonatomic, retain) NSString *city;
#property (nonatomic, retain) NSString *postalCode;
#property (nonatomic, retain) NSString *telNo;
#property (nonatomic, retain) NSString *mobileNo;
+ (id)sharedPersonal;
#end
In the code I save strings to it like so:
PersonalGlobal *sharedPersonal = [PersonalGlobal sharedPersonal];
sharedPersonal.firstName = #"Some string";
But when I change view and try to access the string like this:
PersonalGlobal *sharedPersonal = [PersonalGlobal sharedPersonal];
//Setting some textfield
sometextfield.text = sharedPersonal.firstName;
I get nothing. I have done a #import "PersonalGlobal.h" in all the files.
Can i commit the changes in any way to the singleton class?
Can anyone see what I am doing wrong here?
Thanks!
Your implementation is looking fine. This should work if your singleton returning the only one instance . So the point of doubt in your sharedPersonal method . Just try to add breakpoints in this method and see whether it is creating a new instance every time .for the reference I got this SO question.
If not then you can also try this :
+(SingleTon *)getSharedInstance
{
static PersonalGlobal *sharedPersonalGlobal = nil;
if (sharedPersonalGlobal==nil)
{
sharedPersonalGlobal=[[PersonalGlobal alloc]init];
}
return sharedPersonalGlobal;
}
This is working code for me.
Your singleton implementation looks ok. I wouldn't be surprised if in this case the code that you wrote to set the firstName just never gets executed. If I were you I would step through the codes.

Accessing changeable values in a singleton?

First off, I come from Lua, don't blame me for being global variable minded lol. So, I've been reading up on how to use this whole "Singleton system" and I'm not sure if I'm completely missing the point or if I'm just implementing it incorrectly?
The goal of my code is to create a way for multiple files to access a variable that holds the size of an array in a specific file. Here is my singleton:
.h
#import <Foundation/Foundation.h>
#interface GlobalVariables : NSObject
{
NSNumber *currentGameArrayCount;
BOOL *isGamePaused;
}
#property (nonatomic, readwrite) NSNumber *currentGameArrayCount;
#property (nonatomic, readwrite) BOOL *isGamePaused;
+ (GlobalVariables *)sharedInstance;
#end
.m
#import "GlobalVariables.h"
#implementation GlobalVariables
#synthesize currentGameArrayCount, isGamePaused;
static GlobalVariables *gVariable;
+ (GlobalVariables *)sharedInstance
{
if (gVariable == nil) {
gVariable = [[super allocWithZone:NULL] init];
}
return gVariable;
}
- (id)init
{
self = [super init];
if (self)
{
currentGameArrayCount = [[NSNumber alloc] initWithInt:0];
isGamePaused = NO;
}
return self;
}
#end
and in another file with the array I use:
GlobalVariables *sharedData = [GlobalVariables sharedInstance];
NSNumber *tmpArrayCount = [sharedData currentGameArrayCount];
NSInteger tmpCount = [whereStuffActuallyHappens.subviews count]; // Subviews is the array
NSNumber *currentCount = [NSNumber numberWithInteger:tmpCount];
tmpArrayCount = currentCount;
the hope of this code was to get the variable in the singeton (currentGameArrayCount) and set it too what the current array count was (currentCount). Am I incorrectly interpreting the purpose of a singleton? Am I just bad at singletons and didn't set it up correctly? Does anyone know how I could achieve the result of getting my array count to be accesible to all my files?
You have a few issues. Try these changes:
GlobalVariables.h:
#import <Foundation/Foundation.h>
#interface GlobalVariables : NSObject
#property (nonatomic, assign) int currentGameArrayCount;
#property (nonatomic, assign) BOOL gamePaused;
+ (GlobalVariables *)sharedInstance;
#end
GlobalVariables.m:
#import "GlobalVariables.h"
static GlobalVariables *gVariable = nil;
#implementation GlobalVariables
+ (GlobalVariables *)sharedInstance {
if (gVariable == nil) {
gVariable = [[self alloc] init];
}
return gVariable;
}
- (id)init {
self = [super init];
if (self) {
self.currentGameArrayCount = 0;
self.gamePaused = NO;
}
return self;
}
#end
Now in your other code you can do:
GlobalVariables *sharedData = [GlobalVariables sharedInstance];
int tmpArrayCount = sharedData.currentGameArrayCount;
NSInteger tmpCount = [whereStuffActuallyHappens.subviews count]; // Subviews is the array
sharedData.currentGameArrayCount = tmpCount;

using an NSArray in a custom class isn't working

Starting over. I am fairly new to objective C. I have created the following class and I can't figure out how to initialize the array.
Can anyone provide any guidance on how to initialize the NSArray?
StatusPost.m
#import "StatusPost.h"
#implementation StatusPost
#synthesize messageId, fromName, friendId, message, choice2, choice3, choice4, picture, fbImage, commentCount, commentArray;
-(id)initWithMessageId:(NSString*) rMessageId
fromName:(NSString*) rFromName
friendId:(NSString*) rFriendId
message:(NSString*) rMessage
choice2:(NSString*) rChoice2
choice3:(NSString*) rChoice3
choice4:(NSString*) rChoice4
picture:(NSString *) rPicture
fbImage:(UIImage *)rfbImage
commentCount:(NSString*) rCommentCount
commentArray:(NSArray*) rCommentArray
{
if (self = [super init]) {
commentArray = [NSArray new];
self.messageId = rMessageId;
self.fromName = rFromName;
self.friendId = rFriendId;
self.message = rMessage;
self.choice2 = rChoice2;
self.choice3 = rChoice3;
self.choice4 = rChoice4;
self.picture = rPicture;
self.fbImage = rfbImage;
self.commentCount = rCommentCount;
self.commentArray = rCommentArray;
}
return self;
}
- (void)dealloc {
[messageId release];
[fromName release];
[friendId release];
[message release];
[picture release];
[fbImage release];
[commentCount release];
[commentArray release];
[super dealloc];
}
#end
StatusPost.h:
#import
#interface StatusPost : NSObject {
NSString* messageId;
NSString* fromName;
NSString* friendId;
NSString* message;
NSString* choice2;
NSString* choice3;
NSString* choice4;
NSString* picture;
UIImage* fbImage;
NSString* commentCount;
NSArray* commentArray;
}
#property (nonatomic, retain) NSString* messageId;
#property (nonatomic, retain) NSString* fromName;
#property (nonatomic, retain) NSString* friendId;
#property (nonatomic, retain) NSString* message;
#property (nonatomic, retain) NSString* choice2;
#property (nonatomic, retain) NSString* choice3;
#property (nonatomic, retain) NSString* choice4;
#property (nonatomic, retain) NSString* picture;
#property (nonatomic, retain) UIImage* fbImage;
#property (nonatomic, retain) NSString* commentCount;
#property (nonatomic, retain) NSArray* commentArray;
-(id)initWithMessageId:(NSString*) rMessageId
fromName:(NSString*) rFromName
friendId:(NSString*) rFriendId
message:(NSString*) rMessage
choice2:(NSString*) rChoice2
choice3:(NSString*) rChoice3
choice4:(NSString*) rChoice4
picture:(NSString*) rPicture
fbImage:(UIImage*) rfbImage
commentCount:(NSString*) rCommentCount
commentArray:(NSArray*) rCommentArray;
#end
It is likely that you aren't ever initializing the array, so when you try to add an object, you are just sending a message to nil. In the custom class's init method, add the line:
commentArray = [NSMutableArray new];
[NSArray new] is shorthand for [[NSArray alloc] init], so, technically speaking, that statement "inits" the NSArray.
However, your code looks a bit peculiar. You have the following statements in your init:
commentArray = [NSArray new];
self.commentArray = rCommentArray;
The first statement is setting the instance variable commentArray to the address of the newly alloced/inited NSArray while the second is setting the property commentArray to a parameter value. However, you have (through the #synthesize) made the instance variable commentArray the "backing store" for the property commentArray, so when you execute the second line the effect of the first line is overwritten (and the NSArray you created is "leaked").
(But if your real question is how to "load" an NSArray with values, you should ask that question -- and you'll get different answers.)

I get a "Incorrect decrement of the reference count of an object that is not owned at this point by the caller"

When I do Analyze to find out the potential memory leak, I get a "Incorrect decrement of the reference count of an object that is not owned at this point by the caller" :
- (int)downloadUrlTofolder:(NSString *)url filename:(NSString *)name tryTime:(int)tryTime
{
int result = 0;
GetFtpService *ftpService = [[GetFtpService alloc] initwithUrlandOutPut:url output:name];
//I have delete the code here, but problem is not solved.
[ftpService release]; //the potential problem point to this line
return result;
}
Below is the "initwithUrlandOutPut" method:
- (id)initwithUrlandOutPut:(NSString *)url output:(NSString *)o
{
if(self = [super init]) {
self.urlInput = url;
self.outPath = o;
self.success = [NSString stringWithString:#"success"];
self.connected = nil;
}
return self;
}
And the interface:
#interface GetFtpService : NSObject <NSStreamDelegate>
#property (nonatomic, retain) NSInputStream *networkStream;
#property (nonatomic, copy) NSString *urlInput;
#property (nonatomic, retain) NSInputStream *fileStream;
#property (nonatomic, copy) NSString *outPath;
#property int tryTime;
#property (nonatomic, copy) NSString *success;
#property (nonatomic, copy) NSString *connected;
- (id) initwithUrlandOutPut:(NSString *)url output:(NSString *)o;
I want to know why this happened? and how to fix it?
I suspect it's because the 'w' in "initwith..." is not capitalized. Maybe the analyzer is not recognizing the method as an init method because of that.

EXC_BAD_ACCESS when calling class init in Objective C

I've been trying to figure this out but I can't figure out what I'm doing wrong.
I wrote a class and whenever I try to initialize it, I get a EXC_BAD_ACCESS error. I can't even step into the initialization.
Anyone have any idea what I'm doing wrong?
User *myUser = [myUser init];
.h file:
#import <Foundation/Foundation.h>
#interface User : NSObject {
long rowId;
NSString *email;
NSString *password;
NSString *fileVersion;
}
#property long rowId;
#property (assign) NSString *email;
#property (assign) NSString *password;
#property (assign) NSString *fileVersion;
#end
.m file
#import "User.h"
#implementation User
#synthesize rowId, email, password, fileVersion;
-(id)init {
self = [super init];
return self;
}
#end
You have to actually allocate the object:
User *myUser = [[User alloc] init];
Don't forget to release it when you're done using it.