I am trying to print (nslog) the name of a photo embedded in PhotoView object that I created. I have created 2 viewcontrollers class and the PhotoView class extending the UIButton class to populate a grid in one of the former viewcontrollers.
In PhotoView.h I have
#interface PhotoView : UIButton
#property (assign, nonatomic) NSString *photoName;
...
in PhotoView.m I have
self.tag = [[data objectForKey:#"PhotoID"] intValue];
self.photoName = [data objectForKey:#"PhotoName"];
After printing out the value of tag and photoName on the same file, everything looks good.
Problem start when I try to print the value of photoName from another class after clicking on the PhotoView
-(void)didSelectPhoto:(PhotoView*)sender
{
NSLog(#"%#", [NSString stringWithFormat:#"%#", sender.photoName]);
}
After clicking on the photoView, I get EXC_BAD_ACCESS error.
However, If I do
NSLog(#"%#",[NSNumber numberWithInt:sender.tag]])
I don't get this error.
What could possibly be wrong?
Thanks in advance.
Two remarks:
[NSString stringWithFormat:#"%#", sender.photoName] - No please! No! Don't do that! It's not only superfluous and wastes CPU cycles, but it also heavily decreases readability. if you have a string, you don't have to duplicate it like this, just use the string object directly:
NSLog(#"%#", sender.photoName);
The actual error you have is this:
#property (assign, nonatomic) NSString *photoName;
I. e. you have an assign property, so it doesn't retain its value. When your string object goes out of scope, it's deallocated (and since it's not weak, it isn't automatically set to nil, but it holds whatever garbage value that invalid pointer is, hence the crash). Write instead
#property (retain, nonatomic) NSString *photoName;
if you're not using ARC, and
#property (strong, nonatomic) NSString *photoName;
if you are.
Related
In my header file I declared a new property like this:
#property (weak, nonatomic) NSString *porperty;
In my implementation file I give the property a value:
-method1{
self.property = someString;
NSLog(#"property = %#", self.property);
}
The log shows up in the debugger as the same value of someString. Okay great, but when i try to use this property in the next method of the same implemtation file it loses its value.
-method2{
NSLog(#"property = %#", self.property);
}
Now the debugger says (null).
Simple question. i know but this usually works for me. What am i doing wrong?
This is because someString has been released on next cycle.
Replace weak by strong, this will retain your string.
#property (strong, nonatomic) NSString *porperty;
I want to pass whatever string a user inputs into a UITextField' over to the destination view controller, but when I NSLog the value in the destination, it shows up as null. I'm also getting a warning stating:incompatible pointer types assigning to UITextField from NSString`. How can I properly make the assignment and send it over?
Originating view controller
SearchViewController.m:
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
controller.itemSearch = self.itemSearch.text;
}
SearchViewController.h:
#property (weak, nonatomic) IBOutlet UITextField *itemSearch;
Destination view controller
UserCategoryChooserViewController.h:
#import <UIKit/UIKit.h>
#import "SearchViewController.h"
#interface UserCategoryChooserViewController : UIViewController
#property (weak, nonatomic) IBOutlet UITextField *itemSearch;
UserCategoryChooserViewController.m:
NSLog(#"The text is:'%#'", self.itemSearch.text); // results in (null)
The above two answer are also correct. But if you want to make the assignment properly then modified textfield variable as NSString variable like that below:
#interface UserCategoryChooserViewController:UIViewController
#property (strong, nonatomic) NSString *itemSearch;
After doing this your warning
incompatible pointer types assigning to UITextField from NSString will get removed
controller.itemSearch is a UITextField *, and you tried to set it to a NSString *, that's what that warning is for. To set text of a UITextField, try this:
[controller.itemSearch setText:self.itemSearch.text];
There might be other issues, but let's start from here.
Let's go through the error you are seeing. It says that you are assigning an NSString * to a UITextField *. Unfortunately, you cannot do that. Here, itemSearch is the text field.
To make your code run properly, you need to set the text property of the itemSearch text field. The correct code would be:
controller.itemSearch.text = self.itemSearch.text;
As a side note, you should really not be meddling so deep into iOS development until you have made a strong foundation, which you have not.
Newbie to Objective-C....
I have a real simple .h file:
#interface IdentityManager : NSObject
#property (nonatomic, weak) NSString *username;
#property (nonatomic, weak) NSString *password;
#property (nonatomic, weak) NSString *connString;
#property (nonatomic, weak) NSString *token;
#end
And I want need to grab text from some text fields in another object to load into an Identity object:
self.identity.username = self.usernameTextField.text;
self.identity.password = self.passwordTextField.text;
Yep, it's a login page. Problem is that the username would not be set. After hours trying to find out why, I found that putting the value of self.usernameTextField.text into a local variable and passing the value of that to the Identity object worked:
NSString *tempUsername = self.usernameTextField.text;
self.identity.username = self.tempUsername;
self.identity.password = self.passwordTextField.text;
I have no idea why this would be. I can only guess that all my messing around has somehow left a trace of some old references in Xcode's cache somewhere.
More likely, I'm an idiot. Better, I'm still learning.
Should I be using NSMutableString?
I think something similar is happening again elsewhere. Use of a temp variable helping to achieve my goal.
Any thoughts anyone?
I don't really think your second solution actually fixes the issue. It's probably something else.
Though it's really wrong for a manager class to have a weak reference. In OOP, classes and especially managers should own the object they have as property.
So you should use strong references instead of weak:
#property (nonatomic, strong) NSString *username;
Additionally, you don't want any changes outside the class to modify the variable, so you should be passing a copy of the object:
NSString *username = self.usernameTextField.text;
self.identity.username = [username copy];
Alternatively, you can declare the property as copy instead of strong and you don't have to worry about copying the string every time you set it. (Credit to albertamg)
#property (nonatomic, copy) NSString *username;
I have two core data models with int64_t properties. One of them works fine while the other throws EXC_BAD_ACCESS when I try to assign a non-zero value to the integer field. I've read the answers that say to recreate the NSManagedObject child class and I have done with no success. The broken class looks like this:
#interface NoteObject : NSManagedObject
#property (nonatomic) int64_t remoteID;
#property (nonatomic) int64_t remoteArticleID;
#property (strong, nonatomic) ArticleObject *article;
#property (strong, nonatomic) NSString *status;
#property (strong, nonatomic) NSString *token;
#property (strong, nonatomic) NSString *title;
#property (strong, nonatomic) NSString *noteContent;
#property (strong, nonatomic) NSDate *pubDate;
#property (strong, nonatomic) NSDate *modDate;
#end
#implementation NoteObject
#dynamic remoteID;
#dynamic remoteArticleID;
#dynamic article;
#dynamic status;
#dynamic token;
#dynamic title;
#dynamic noteContent;
#dynamic pubDate;
#dynamic modDate;
#end
The offending line is in this block:
_noteObject = [NSEntityDescription insertNewObjectForEntityForName:#"Note" inManagedObjectContext:self.managedObjectContext];
_noteObject.remoteArticleID = 0; // this works
_noteObject.remoteArticleID = 1; // this crashes
What really has me stumped is that in another model I have the same fields with the same types and they will accept non-zero values without any trouble:
bookmarkObject = [NSEntityDescription insertNewObjectForEntityForName:#"Bookmark" inManagedObjectContext:self.managedObjectContext];
bookmarkObject.remoteArticleID = 0; // this works
bookmarkObject.remoteArticleID = 1; // this works, too
Is there anything in my .xcdatamodeld file that could be causing this?
EDIT
My data models look like this:
I had exactly the same problem.
It appears that xcode (or perhaps the compiler, or perhaps the two between them) sometimes gets confused when you manually edit properties in the NSManagedObject - it ends up treating our integers as pointers and trying to access memory directly - hence the EXC_BAD_ACCESS.
Anyway, as this question explains: SO Question, the solution is to delete your old class (obviously copy out any custom code so you can paste it back again later) and then get xcode to regenerate it for you (select the entity in the data model and select "Editor / Create NSManagedObject subclass..."). In the dialogue that appears, make sure "Use scalar properties for primitive data types" is ticked.
You may have to manually edit the resulting class to turn some non scalar properties back into objects (I had a date object which it turned into something other than NSDate - I forget exactly what, but it accepted the manually made edit back to NSDate).
It worked for me. Hope it works for you.
Ali
Well, in case anyone else is having this issue, I never found a satisfactory answer for why one entity was working and the other wasn't. My workaround was to refactor the properties to use NSNumber wrappers instead of primitive int64_t values.
#property (strong, nonatomic) NSNumber *remoteID;
#property (strong, nonatomic) NSNumber *remoteArticleID;
Of course, that means boxing/unboxing the integer values.
_noteObject.remoteArticleID = [NSNumber numberWithInt:1];
int intVar = [_noteObject.remoteArticleID intValue];
In your model file, check that the entity's "Class" property is set to the appropriate class, and not the default NSManagedObject.
If you leave it as NSManagedObject, Core Data will create properties itself on a custom NSManagedObject subclass it generates itself, rather than using your own subclass. Most getters and setters will appear to work, but you may have issues with non-boxed primitive properties and custom getters and setters.
This is my first time using this site and I am quite new to Objective-c. I'm sure this is a simple question but for some reason I am having a lot of issues. The app is designed to have the user enter a string via textfield, then it will pick the rest of the sentence and display it. The issue appears to be that my *name will be retained after the keyboard method and work once in the changelabel method. Then if i press the button again, invoking the changelabel method, the name appears to have been released and crashes the app.
#import
#import "Array.h"
#interface RandomBoredViewController : UIViewController {
UILabel *label;
UIButton *button;
UITextField *textField;
Array *array;
NSString *name;
NSString *description;
NSMutableString *whole;
}
#property (nonatomic, retain) IBOutlet UILabel *label;
#property (nonatomic, retain) IBOutlet UIButton *button;
#property (nonatomic, retain) IBOutlet UITextField *textField;
#property (nonatomic, retain) Array *array;
#property (nonatomic, retain) NSString *name;
#property (nonatomic, retain) NSString *description;
#property (nonatomic, retain) NSMutableString *whole;
-(IBAction) keyBoard;
-(IBAction) changeLabel;
#end
and my .m
#import "RandomBoredViewController.h"
#implementation RandomBoredViewController
#synthesize label;
#synthesize checker;
#synthesize button;
#synthesize textField;
#synthesize array;
#synthesize name;
#synthesize description;
#synthesize whole;
-(IBAction) changeLabel {
NSLog(#"Button being pushed");
description = [array getString];
NSLog(#"%#",description);
NSLog(#"%#",name);
name = [NSString stringWithString:name];
whole = [NSMutableString stringWithString:name];
NSLog(#"%#",name);
NSLog(#"%#",whole);
[whole appendString:description];
NSLog(#"%#",name);
NSLog(#"%#",whole);
label.text = whole;
NSLog(#"%#",name);
}
-(IBAction) keyBoard {
name = [NSString stringWithString:textField.text];
NSLog(#"%#",name);
label.text = [NSString stringWithString: name];
[textField resignFirstResponder];
}
- (void)viewDidLoad {
[super viewDidLoad];
array = [[Array alloc]init];
[array createArray];
NSLog(#"%i",[array arrayCount]);
whole = [[NSMutableString alloc]init];
name = [[NSString alloc]init];
}
- (void)dealloc {
[super dealloc];
[label release];
[button release];
[textField release];
[array release];
//[name release];
[description release];
}
#end
You are setting name to an autoreleased instance of NSString, this is probably what's causing your app to crash.
Use
self.name = [NSString stringWithString:textField.text];
Your synthesized mutator will retain the NSString and prevent it from being released.
Taking one thing in microcosm, the code you've posted creates two things named name — an instance variable and a property.
Instance variables are directly accessed storage. They have no behaviour.
Properties are named attributes accessed via getters and setters. So they may have arbitrary behaviour. They may report the values of instance variables or values calculated from instance variables or values calculated or obtained by any other means. Relevantly, the setters may retain, assign or act in any other way.
Instance variables may be accessed only by the instance of a class they belong to. Properties are usually intended to be accessed by anyone.
Since retaining is a behaviour and you've ascribed it to your name property, setting something to it would result in a retain. Instance variables can't have behaviour, so setting a value to it doesn't result in a retain or anything else.
As a result, this line:
name = [NSString stringWithString:name];
Creates a new string and returns a non-owning reference. Which means it'll definitely last for the duration of this autorelease pool (ie, you explicitly may pass it as an argument or return it safely, assuming you haven't taken manual control of your autorelease pools).
You store that reference to your instance variable. Instance variables don't have behaviour so the reference is stored but you still don't own that object. It's still only safe to use for the duration of that autorelease pool.
So when you access it in that method it's safe. When you access it later it's unsafe.
If instead you'd gone with:
self.name = [NSString stringWithString:name];
Then you'd have set that string to be the new value of the property. Because your property has the retain behaviour, you'd subsequently have completely safe access to the string object, until you say otherwise.
Because you've got a property with exactly the same name as an instance variable, you could subsequently access it either as just name or as self.name. Similarly you could have stored directly to the instance variable rather than via the property if you'd ensured you had an owning reference manually.
As suggested above, use of ARC is a way to get the compiler to figure all this stuff out for you.
That issue is what causes your code to crash — you end up trying to access a reference that has ceased to be valid. If you'd taken ownership of it then it would have continued to exist at least as long as you kept ownership.
try using self.name
sometimes this stuff confuses me as well and for that you might want to consider using arc in which case most of this stuff can be avoided.
when using properties you should always use self.propertyName vs propertyName (only), it uses the accessors (get propertyName, set propertyName) as opposed to directly accessing that pointers value.
take in mind there are 2 exceptions to the rule, init and dealloc which should NOT use self.
self.name = [NSString stringWithString:name];
you technically should also have an init method
to initialize your variables, and i believe you should call [super dealloc] last not first in your dealloc method, but thats not your problem and might not matter (just what I do when I dont use arc)
When you change your instance variable in changeLabel, you should release the previous value and retain the new one. You may use the accessors to perform the memory management stuff for you. Also, I think you should invoke [super dealloc] after releasing the instance variables in your implementation of dealloc.
If you're not familiar with Cocoa memory management (and even if you are), the best is to enable ARC (Automatic Reference Counting) and let the compiler deal with it.