Objective-c: AppDelegate NSString - iphone

I have an NSString that as an instance variable within my appdelegate as below:
distributedLCAAppDelegate.h:
#class distributedLCAViewController;
#interface distributedLCAAppDelegate : NSObject <UIApplicationDelegate> {
UIWindow *window;
distributedLCAViewController *viewController;
NSString *token;
}
#property (nonatomic, retain) IBOutlet UIWindow *window;
#property (nonatomic, retain) IBOutlet distributedLCAViewController *viewController;
#property (nonatomic, copy) NSString *token;
#end
section from distributedLCAAppDelegate.m:
#implementation distributedLCAAppDelegate
#synthesize window;
#synthesize viewController;
#synthesize token;
- (void)application:(UIApplication *)app didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
token = [NSString stringWithFormat:#"%#",deviceToken];
token = [token stringByReplacingOccurrencesOfString:#" " withString:#""];
token = [token substringWithRange:NSMakeRange(1, [token length]-2)];
}
I need to be able to use this token variable within the view controller. Currently this is what I have:
section from within distributedLCAViewController.m:
- (IBAction)switchWasActivated:(id)sender
{
NSString *token2 = [[[distributedLCAAppDelegate alloc] token] autorelease];
}
However, token2 = "invalid cfstringref".
I initially tried declaring a public method called getToken, which just returned token. But I was getting the same problem in that case as well.
Any help would be appreciated!

Try this : (UPDATED) (fixed)
NSString* token2 = ((distributedLCAAppDelegate*)[[UIApplication sharedApplication] delegate]).token;

Try following -
- (IBAction)switchWasActivated:(id)sender {
distributedLCAAppDelegate *delegate = (distributedLCAAppDelegate *) [[UIApplication sharedApplication] delegate];
NSString *token2 = delegate.token;
}

Can you check the Files' Owner in "MainWindow.xib" if its delegate outlet is set to your distributedLCAAppDelegate? Just Ctrl-click on the yellow box-icon in Interface Builder.

distributedLCAAppDelegate* delegateobj = [(distributedLCAAppDelegate*)[UIApplication sharedApplication] delegate];
NSString *token_ = delegateobj.token;
NSLog(#"token_ :%#",token_);
Try This , it should work

Related

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

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.

EXC_BAD_ACCESS Code=2 when using a Singleton

I have a Singleton to manage some variables I need in various places in my app. This is the singleton, called General:
#import "General.h"
static General *sharedMyManager = nil;
#implementation General
#synthesize user;
#synthesize lon;
#synthesize lat;
#synthesize car;
#synthesize firstmess;
#synthesize firstfrom;
#synthesize numcels;
#pragma mark Singleton Methods
+ (id)sharedManager {
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
if (sharedMyManager == nil) {
sharedMyManager = [[self alloc] init];
}
});
return sharedMyManager;
}
- (id)init {
if (self = [super init]) {
user = [[NSString alloc] initWithString:#"vacio"];
numcels=0;
}
return self;
}
- (void)dealloc {
// Should never be called, but just here for clarity really.
}
#end
I use it in a TableView that present in screen messages of a part of my app that is a chat.
I mean, everytime the app receives or send a message, i add 1 to the var "numcels", and that is the value that numberOfRowsInSection method returns.
-(NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
General *general = [General sharedManager];
return *(general.numcels); //It freezes here
}
The problem is, when i run the program, it freezes at the commented line, saying EXC_BAD_ACCESS code=2. I guess that the problema may be with the singleton, but don't know where it is exactly.
Any help? Thank you in advance.
-------EDIT--------
-(UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSLog(#"Hemos entrado en cellForRowAtIndexPath");
UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:#"UITableViewCell"];
if(!cell){
UITableViewCell *cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:#"UITableViewCell"];
}
General *general = [General sharedManager];
NSString *text=general.firstmess;//it crashes now here
NSString *remite=general.firstfrom;
[[cell textLabel]setText:remite];
[[cell detailTextLabel] setText:text];
return cell;
}
And the General.h, by request:
#import <Foundation/Foundation.h>
#interface General : NSObject {
NSString *user;
double lat;
double lon;
}
#property (nonatomic, retain) NSString *user;
#property (assign, nonatomic) double lat;
#property (assign, nonatomic) double lon;
#property (assign, nonatomic) Boolean car;
#property (assign, nonatomic) NSString *firstmess;
#property (assign, nonatomic) NSString *firstfrom;
#property (assign, nonatomic) int numcels;
+ (id)sharedManager;
#end
It should be like the following:
return general.numcels;
numcels is an integer and you cannot apply the * operator to it.
After solving the first issue (thanks to the kind help of Ankit), it crashed in the line I have commented below the EDIT. I simply changed
#property (nonatomc, assign) NSString *firstmess;
to
#property (retain, nonatomic) NSString *firstmess;
And it doesn't crash anymore.
Thank you!

NSCFNumber unrecognized selector

i want to send data between views, but i get an error: unrecognized selector....
and the in the debugger, the variable mystring is a NSCFNumber ("at this time") instead of NSString...
allergy_appAppDelegate.h
#import <UIKit/UIKit.h>
#interface allergy_appAppDelegate : NSObject <UIApplicationDelegate, UITabBarControllerDelegate> {
UIWindow *window;
UITabBarController *tabBarController;
NSMutableArray *result_array;
}
#property (nonatomic, retain) IBOutlet UIWindow *window;
#property (nonatomic, retain) IBOutlet UITabBarController *tabBarController;
#property (copy , readwrite) NSMutableArray *result_array;
#end
viewcontroller.m
allergy_appAppDelegate *dataCenter = (allergy_appAppDelegate *)[[UIApplication sharedApplication]delegate];
dataCenter.result_array = [[NSMutableArray alloc] initWithArray:Parser_result];
result.m
allergy_appAppDelegate *dataCenter = (allergy_appAppDelegate*)[[UIApplication sharedApplication]delegate];
show_user_array = [[NSMutableArray alloc] initWithArray: dataCenter.result_array]
for (NSString *mystring in show_user_array) {
textView.text = [[textView text] stringByAppendingString:#"\n"];
textView.text = [[textView text] stringByAppendingString:mystring];
}
Instance variables should be camel-cased, not have _. I.e. result_array should be resultArray. Classes start with capital letters.
Are you sure your result array is full of instances of NSString or NSNumber (or whatever you need)?
Given that you are leaking the array here...
dataCenter.result_array = [[NSMutableArray alloc] initWithArray:Parser_result];
... it is unlikely that this is an over-release problem. Note also that copy with NSMutableArray won't do what you want (the compiler should flag it, but doesn't). -copy always returns an immutable copy of an instance of a class cluster.

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.

trying to set a delegate method to get urlConnection data

I've been going around and around, I've been trying to use this example but running into trouble in the delegate method. I'm trying to figure out how to close this out. Looks like I've got a lot set correctly but need help on final step:
I'm getting a -[ThirdTab apiFinished:]: unrecognized selector sent to instance.
On line two of the WebServiceAPI.m : the self.aDelegate =aDelegate is giving me an error:
2) Local declaration of aDelegate hides instance variable.
This is my first go around with using delegates like this an can't figure out this error.
Thanks.
This is in my ThirdTab UITableViewController:
-(void)viewDidLoad {
[super viewDidLoad];
WebServiceAPI *api = [[WebServiceAPI alloc] init];;
api.delegate =self;
[api DataRequest:data3 delegate:self];
// this is where I'm trying to connect data3 to my tableview.
self.tableDataSource3 = [data3 objectForKey:#"Rows"];
self.webApi = api;
[api release];
This is the WebServiceAPI.h:
#import <UIKit/UIKit.h>
#class WebServiceAPI;
#protocol WebServiceAPIDelegate;
#interface WebServiceAPI : NSObject
{
id<WebServiceAPIDelegate>aDelegate;
NSDictionary *data3;
NSArray *rowsArrayFamily;
NSMutableData *receivedData;
NSString *jsonreturnFF;
}
#property (nonatomic, assign) id<WebServiceAPIDelegate>aDelegate;
#property (nonatomic, retain) NSDictionary *data3;
#property (retain,nonatomic) NSArray *rowsArrayFamily;
#property (nonatomic, retain) NSMutableData *receivedData;
#property (nonatomic, retain) NSString *jsonreturnFF;
- (void) DataRequest: (id) aDelegate;
#end
#protocol WebServiceAPIDelegate
#required
-(void)apiFinished:(WebServiceAPI*)api;
-(void)api:(WebServiceAPI*)api failedWithError:(NSError*)error;
#end
Here is the WebServiceAPI.m where I'm having the issue:
- (void) DataRequest:data3 delegate:(id) aDelegate; {
self.aDelegate = aDelegate;
NSUserDefaults *defaultsF = [NSUserDefaults standardUserDefaults];
NSString *useridFF = [defaultsF objectForKey:kUseridKey];
NSString *urlstrF = [[NSString alloc] initWithFormat:#"http://www.~.php?userid=%#",useridFF];
NSURLRequest *req3 =[NSURLRequest requestWithURL:[NSURL URLWithString:urlstrF]];
NSURLConnection *conn3 = [[NSURLConnection alloc] initWithRequest:req3 delegate:self];
NSMutableData *data =[[NSMutableData alloc] init];
self.receivedData = data;
// self.connection = conn3;
}
Your WebService.h declares a property:
#property (nonatomic, assign) id<WebServiceAPIDelegate>aDelegate;
Your WebService.m uses a different property:
self.delegate = aDelegate;
You can either change the name of the property to delegate in WebService.h, or use the current name of the property in WebService.m.