Why am I getting a "no visible #interface message for 'NSDecimalNumber' declares the selector" for my method? - iphone

I must be missing something simple here. Anyway, I started out by just making a regular function,
NSDecimalNumber* aa(NSMutableString *string)
{code}
which I would then call by pressing a button like so:
- (IBAction)parse:(id)sender {
string1=[NSMutableString stringWithFormat:#"%#", screen.text];
NSDecimalNumber *output=aa(string1);}
(screen.text is from a label) However, partway into it, I realized that the function can't use variables from the rest of my viewcontroller.m class (and vice-versa), so I decided to implement the function as a method instead. Here's what I did. First, I added this to viewcontroller.h,
+ (NSDecimalNumber*) aa:(NSMutableString*) string;
#property (nonatomic, strong) NSDecimalNumber *number; //the number I'm working with
synthesized my property, changed my function declaration to this,
+ (NSDecimalNumber*) aa:(NSMutableString*) string
and attempted to call it like this,
NSDecimalNumber *output=[[NSDecimalNumber alloc] aa:string1];
With that attempt, I got two errors -- "No visible #interface for 'NSDecimalNumber' declares the selector 'aa,'" and "instance variable 'number' accessed in class method."
So I tried again with an instance method. Changed the +'s to -'s and instead called the method with
NSDecimalNumber *output;
[output aa:string1];
That corrected the second error but not the first one. I can't figure out why it isn't recognizing the method in the #interface. Also, those weren't the only things I've tried changing -- I've been playing around with multiple ways to call the method, but nothing seems to work. Any ideas?

This function call:
NSDecimalNumber *output=[[NSDecimalNumber alloc] aa:string1];
..is attempting to call aa an instance of NSDecimalNumber. I don't think that's what you want, isn't your aa method a member of your class? Also, you're not calling a class initializer (although you don't need to, since your method is static so long as its definition starts with +):
// MyClass method definition
+ (NSDecimalNumber*) aa:(NSMutableString*) string
// Called with
NSDecimalNumber *output=[MyClass aa:string1];
--UPDATE--
To address the "instance variable" error, you need to make the method an instance method. Change + in definition to - and call it thusly:
// MyClass method definition
- (NSDecimalNumber*) aa:(NSMutableString*) string
// Call it like this _if calling from within MyClass only_ (hence, "self")
NSDecimalNumber *output = [self aa:string];

If you want to add methods to NSDecimalNumber, you need to use a category. Your code adds a method to your view controller subclass.

Related

concepts of properties with corresponding ivars

i have a general question about properties and ivars.
ive seen many different examples to use properties and it confuses me a bit.
method 1 only using a property without a corresponding ivar.
#property (...) Type *name;
#synthesize name;
method 2 using a property and an ivar
#interface{
Type *ivarName;
}
#property (...) Type *name;
#synthesize name = ivarName;
method 3 ignoring properties and working with ivars
#interface{
Type *ivarName;
}
ivar = ...;
i currently use method 1 for most things i do, it just works. but i have startet to wonder if i might be missing something here. i have read a lot of questions about ivars VS properties, but none of them seemed to really care about how they work together.
in most sample projects i've seen method 2 is used. so my question is: is there any advantage in defining a property and an ivar, and then assign the property to the ivar, than just having a property?
is the solution as simple as: only with a property can an ivar be set from 'outside'?
i have read: Must every ivar be a property? and Property vs. ivar in times of ARC but was not able to draw a final conclusion.
is the solution as simple as: only with a property can an ivar be set from 'outside'?
Essentially, yes. Ivars in Obj-C are (by default) "protected", meaning that the compiler won't allow you to access them externally to the object's own code. For example, given the following class declaration:
#interface Dunstable : NSObject
{
NSString * crunk;
}
#end
You might think you'd be able to access the ivar after creating the object, but trying results in an error:
Dunstable * d = [[Dunstable alloc] init];
d->crunk = #"Forsooth"; // Error: "Instance variable 'crunk' is protected
That's why ObjC uses accessor methods. Defining them manually was mandatory before the advent of declared properties:
#implementation Dunstable
- (NSString *)crunk {
return crunk; // implicit ivar access, i.e. self->crunk
}
- (void)setCrunk: (NSString *)newCrunk {
[newCrunk retain];
[crunk release];
crunk = newCrunk;
}
#end
Now, using the #property and #synthesize directives creates those accessor methods for you (as well as the variable itself). (The manual memory management in the setter is of course also obsolete under ARC.)
It is possible to make an ivar that's accessible from outside the object:
#interface Dunstable : NSObject
{
#public
NSNumber * nonce;
}
#end
Dunstable * d = [[Dunstable alloc] init];
d->nonce = [NSNumber numberWithInt:2]; // Works fine
but this isn't considered good Objective-C style.
The Objective-C Programming Language doc contains a "Historical Note" about this:
Note: Historically, the interface required declarations of a class’s instance variables, the data structures that are part of each instance of the class. These were declared in braces after the #interface declaration and before method declarations:
[...]
Instance variables represent an implementation detail, and should typically not be accessed outside of the class itself. Moreover, you can declare them in the implementation block or synthesize them using declared properties. Typically you should not, therefore, declare instance variables in the public interface and so you should omit the braces.
This is a pretty big change (I was actually surprised that there's no syntax given for ivars declared in #interface anymore in that doc), but it's definitely for the better. You should use declared properties; they do the right thing and make your code cleaner and safer.
When you write:
#synthesize name;
an ivar name is created, and it has the same name as the property. So you can access it with or without self.
In reality if you write
self.name = #"hello";
you are accessing the property, and if you write
name = #"hello";
you are accessing the ivar. Most people (including me) will advise you not to access your ivars directly unless it is really what you want: for example, if you are creating a custom setter or getter for the property. Otherwise always access the property with self.
In my case I always do:
#synthesize name = _name;
The advantage of this approach is that when you forget to write self instead of accessing the ivar you will get an error telling you that the ivar name doesn't exist.
You should never access ivars directly from outside of a class. That's the main function of properties--defining accessor methods for use by other objects. However, it's also good practice to use your accessors from within the same class--this way you can ensure that any appropriate side effects take place (memory management is an obvious example, if you aren't using ARC).
So, Method 3 is usually wrong. Method 1 is roughly equivalent to Method 2--that is, behind the scenes, the runtime is basically creating an ivar for you. Note also that you can set the name of that ivar even if you didn't explicitly define it:
#interface{
//No ivar here!
}
#property (...) Type *name;
#synthesize name = ivarName;
From the second link you supplied, Property vs. ivar in times of ARC, the comment by Denis Mikhaylov on the accepted answer is very telling. He points out that with your case 3, that you can access the iVar through:
classInstance->iVar = #"New value"
But this is considered bad practice. So i'd restate your point as:
Only with a property should an ivar be set from 'outside'

iPhone Int with NSObject &/causes class can't reference itself

I've got a function called updateTheValue() that I have called using [self updateTheValue] for a while now. Two things happened recently; I added the method calling in the viewDidLoad() method and it spit out a warning saying my class may not respond to this. Second, I want to pass objects to updateTheValue() like strings, but mostly ints, so I declared an NSObject to pass into the method. Can an int fit into an NSObject slot, or what should I use instead?
I would have posted these seperately but they seem to be related since after updating updateTheValue() to accept an NSObject every reference to this function turns out the error that my class "May not respond to -updateTheValue"
You could make your method like this:
-(void)updateTheValue:(NSObject *)anObject
// or use -(void)updateTheValue:(id)anObject
{
if ([anObject isKindOfClass:[NSString class]]) {
// Do your string handling here
}
else if ([anObject isKindOfClass:[NSNumber class]]) {
// Do your number handling here
}
}
Use it like this:
[self updateTheValue:[NSNumber numberWithInt:42]];
I'd suggest doing two different methods though, i.e. updateTheValueWithInt: and updateTheValueWithString: making it easier to read and understand.
Make sure you make the method signature visible before using them, so that the compiler knows what this does.
If you use separate methods you can use int directly without wrapping them into NSNumber objects.
First problem:
updateTheValue() must be declared before you try to call it.
You can either move the definition of function before the calls to it, or add a prototype at the top - eg, add:
(void) updateTheValue;
near the top.
Second problem:
Use an NSNumber, eg [NSNumber numberWithInt:45];

Difference between class property mVar and instance variable self.mVar

I am some what confused as to the difference between accessing an instance variable via self or just by name (when working inside the class).
For instance, take this class:
//In .h file:
#interface Register : NSObject {
NSString *mName;
}
- (id) initWithName:(NSString *) name;
//In .m file:
- (id) initWithName:(NSString *)name
{
if (self == [super init])
{
mName = name;
}
return self;
}
What's the difference between accessing the instance variable via
self.mName = name;
vs
mName = name;
Which isn't a #property and is not #sythenize'd.
Say it is this though, per this example:
//In .h file:
#interface Manange_My_ViewsViewController : UIViewController {
IBOutlet UILabel *countLabel;
}
#property (nonatomic, retain) IBOutlet UILabel *countLabel;
//In .m file:
#synthesize countLabel;
- (void) updateLabel:(NSUInteger)count
{
countLabel.text = [NSString stringWithFormat:#"%d", count];
}
But say I accessed countLabel as:
self.countLabel
What would be the difference?
Edit: Third example per users' answer:
Say it the iVar wasn't an IBOutlet:
//In .h file:
#interface Fake : NSObject {
NSString *mVar;
}
#property (nonatomic, retain) NSString *mVar;
//In .m file:
#synthesize mVar;
mVar = #"";
VS
self.mVar = #"";
Or is it the same - that in the first we are accessing the actual instance variable and in the second we're actually going through the auto created setter (via #synthesize)?
Thanks all!
Edit: Update in response to Peter Hosey ...
So your thinking the convention of mVarName is bad? I took that from my C++ days.
But what about the case when you do?
-(void) someMethod:(int) x
{
x = x;
}
You can't do that (Say 'x' is also a class variable)
But you can do:
-(void) someMethod:(int) x
{
mX = x;
}
But your saying its better to do:
-(void) someMethod:(int) x
{
self.x = x;
}
What's the difference between accessing the instance variable via
self.mName = name;
vs
mName = name;
The first is property access syntax. It translates to an accessor message to the object (in this case, self). That is, that statement implicitly translates to this message expression statement:
[self setMName:name];
(Awkward accessor names like that are why “mName” is a poor name for a property. There is property declaration syntax to work around that, letting you name the property “name” and your instance variable “mName” and map one to the other.)
The second example directly accesses the instance variable—no accessor message.
Which isn't a #property and is not #sythenize'd.
Say it is this though, …
If no property named “mName” is declared for a class, then you can't use property access syntax to access a property by that name on an instance of that class.
And it doesn't matter whether you synthesize the accessors, hand-wave them to a superclass with #dynamic, or define them yourself. That's how the object will respond to the accessor message, but the accessor message the compiler generates will be no different (since a property access could just as easily come from outside the class as from inside it).
Say it the iVar wasn't an IBOutlet:
That doesn't matter. IBOutlet only means anything to IB. Everything else doesn't care.
In fact, IBOutlet is currently just a macro that expands to nothing. After your code gets preprocessed, the word “IBOutlet” is no longer there, so the compiler never sees it. That's how little a difference it makes to anything but IB: None at all.
Edit in response to question edit
I said mName is bad as a property name, because of the accessor names that follow from it. The name of an instance variable is a separate issue, particularly since the property and ivar don't have to have the same name.
For a variable, be it an instance variable or a local variable, the choice of name or m_name or mName is purely a style choice.
someMethod: is generally the accessor, setX:. Within that method, self.x = x, which is [self setX:x], causes infinite recursion. So don't do that.
When someMethod: isn't the accessor (or init or dealloc), using the property is just fine and generally preferable. However, in that case, you're not likely to give one of its arguments the same name as an instance variable. When such a case could occur, name the local variable more specifically, because its purpose is more specific. This, too, is a style issue.
When it is the accessor, I name the local variable newX, having named the instance variable the same as the property, x. This is my own personal style; as I said, naming the property x, the ivar mX, and the local variable x is fine too (aside from the excessive brevity of this example).
OK, first off is the basic difference:
mVar = var;
This is just changing a value. That's it.
self.mVar = var;
This is equivalent to:
[self setMVar:var];
In other words, one invokes a method, the other does not. Using the #property syntax can give you some really neat benefits. For example, you get key-value coding compliance for free. That means that another object can observe this object's mVar property, and be automatically notified whenever it changes, without you doing anything. You don't get this if you just access the ivar directly. (Unless, of course, you implement it yourself. But why would you do that?)
You also get semi-free memory management. If you declare a property as (retain), then you don't have to [newValue retain] yourself. The synthesized method will do this for you (in both cases, you'd still have to [ivar release] in your dealloc method).
You also can get some degree of thread safety. If you don't declare a property as (nonatomic), then it is (by default) atomic (although that keyword does not exist; it's implied). That means that reading/updating the value of the property is an atomic operation. If you were to just access the ivar directly, you'd have to implement the atomicity yourself with a lock.
Basically, using the synthesized methods gets you some really neat stuff for free. The only reason I'd say to not use the #property syntax is if you have irrefutable evidence that invoking those methods is a bottleneck in your code. However, you'll be really hard pressed to come up with a situation where that would be the case.
First of all, with a read-only property--which an IBOutlet essentially is--it does not matter as much.
The key difference is that the property is actually calling the accessor method while the instance variable is being accessed directly.
Thus, for setting a retain property, using self and the accessor will release the old object and retain the new one. Setting the instance variable directly will NOT impact the retain counts of any objects.
Using #synthesize will generate standard accessors for you.
The key reason to use properties is that, since they are accessors, they can be read and/or modified from outside the class.

iPhone ivar naming convention [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How does an underscore in front of a variable in a cocoa objective-c class work?
I've noticed that in a lot of the reference materials out there, I see that a lot of the time, variables are named _variable in the .h file, then are #synthesize'd in the .m file as
#synthesize variable = _variable;
Why is this done? What am I missing?
Thanks!
There is not consensus on this. Some people like to use it for clarity to separate out class variables, and as another responder noted to avoid conflict with incoming parameter names. Even in Apple sample code the use is mixed.
However, I greatly prefer to not use the _ prefix and have two strong reasons:
1) Some people think the _ is a good indicator of "private". My take is that NO class local variable should be accessed without a setter/getter (property) and thus they are ALL private - given that why not name them in a way easier to read and use autocomplete on? Any overlap in names from parameters is quickly revealed by the compiler, and avoided through more thoughtful naming of parameters (or internal variables).
2) (even better reason) - if you use "refactor" in XCode on an internal class var that is named the same as the property used to access it, the property and synthesize statement will also be renamed. If you use refactor on a class variable prefixed with an _, the property name will not be changed - just the synthesize mapping to the internal name. I pretty much never want the name to vary from the property to the real variable it exposes access to. That alone makes me never want to use _ as a variable prefix, since being able to shift names is just about the most useful thing you can do to improve code clarity.
Using that syntax is an option to make it more clear that the ivar and property are different things.
To code external to the class, there is no difference since it uses the property.
For code in the implementation of the class itself, it can make it more clear when the ivar is used versus the property.
For example, say we have an ivar/property for an NSNumber object:
#interface MyClass : NSObject {
NSNumber *num;
}
#property (nonatomic, retain) NSNumber *num;
- (void)doSomething;
#end
#implementation MyClass
#synthesize num;
- (void)doSomething {
// set the property, num is properly retained
self.num = [NSNumber numberWithInteger:1];
// accidentally set the ivar, num is NOT retained
num = [NSNumber numberWithInteger:2];
}
#end
and now using a different name for the ivar and property:
#interface MyClass : NSObject {
NSNumber *i_num;
}
#property (nonatomic, retain) NSNumber *num;
- (void)doSomething;
#end
#implementation MyClass
#synthesize num = i_num;
- (void)doSomething {
// set the property, num is properly retained
self.num = [NSNumber numberWithInteger:1];
// compiler error, there is no ivar named "num"
num = [NSNumber numberWithInteger:2];
// set the ivar, so it needs to be a retained object
i_num = [[NSNumber alloc] initWithInteger:3];
}
#end
Previous answers are missing the history behind this. Before Objective-C 2.0, there were no properties. So you’d have an object with instance variables like this:
#interface MyObject: NSObject {
NSArray *myArray;
}
#end
But how would you access them from other objects? the solution was to make setters and getters. But to avoid confusion, they would do it like this:
#interface MyObject: NSObject {
NSArray *_myArray;
}
- (NSArray *)myArray;
- (void)setMyArray:(NSArray *)myArray;
#end
The _ serves to clear up confusion between the instance variable _myArray and the method -myArray.
Sometimes people use mVarName (C++) and in Obj-c the style seems to be _varName.
One problem you can have, is imagine that your argument to a function is ...set:(int) x - BUT - you have an iVar called x...well your going to get the compiler crying about stuff like that - not to mention its confusing.
The m,_, whatever helps to show what are member properties of the class.
-(void) set:(int)x
{
x = x; // x is an ivar! heh
}
VS
-(void) set:(int)x
{
_x = x; // ahh I see!
}
This is purely convention. I suppose its common because when you make a method getter call like this:
[myObject variable]
you are actually calling a method, not accessing a variable directly. the _ in front makes it clear that you are talking about a variable. Personally, I find this syntax annoying and distracting. I find it unnecessary, but you are right, it does appear here and there.
I prefer not to use the '_' prefix because Apple does use it consistently. By avoiding the prefix I then have greater confidence that my ivars do not collide with Apple's when I extend a cocoa touch class. Since we do not have access to the base class' source this is really the only way I know of to avoid accidental reuse of existing private ivars.
Much like
Method names beginning with “_”, a single underscore character, are reserved for use by Apple.
My preference, following Google, is simply to append an underscore and explicitly synthesize (even if I'm reimplementing):
#synthesize varName=varName_;
If I see that trailing underscore outside of init..., dealloc or an accessor, I know something's fishy.

How to call a method without an instantiated object

This is an objective-c question.
I would like to call a method in an object, but there is no instantiation of the object. Is this possible?
The method I want to call is not a class method.
You can't call a method on an object that doesn't exist. But you can call a method on a class even if you have no instantiated objects of that class. (That's what alloc is in #fbrereton's answer -- a class method).
Class methods are declared and defined with a + instead of a -, are called on the class rather than the instance, and cannot access self or any instance variables in the class (for reasons that should be obvious).
Unless the method is static you will not be able to do this. static routines in Objective-C will be prepended with a +. For example NSObject provides these two routines (among many):
+ (id)alloc; // static - an NSObject instance is not required
- (NSString*)description; // nonstatic - an NSObject instance is required
One would make the respective calls like so:
NSObject* result = [NSObject alloc];
NSString* desc = [result description];
Sorry to nit-pick Chris' terminology, but we don't call a method on an object in Objective-C, we send a message to an object. When you send a message, the runtime will look up the appropriate method and call it. The distinction matters.
Perhaps you just want a plain-old C function. If you don't want a class method, and you don't want an instance method, that appears to be your only option. Don't be afraid of using C functions in Objective-C. Every technique has its place.
You can indeed invoke an instance method without an instance, provided it is functionally a class method (that is, it accesses no instance variables). Here's an example:
/*
Compile with:
gcc -framework Foundation inst_method_without_inst.m -o inst_method_without_inst
*/
#import <Foundation/Foundation.h>
#import <objc/runtime.h>
#interface Foo : NSObject {
}
- (BOOL)doSomethingWithThis:(NSString *)this;
#end
#implementation Foo
- (BOOL)doSomethingWithThis:(NSString *)this {
NSLog(#"Look, it's this: %#", this);
return YES;
}
#end
typedef BOOL (*my_sel_t)(id, SEL, NSString *);
int
main(void) {
Class cls = [Foo class];
SEL my_sel = #selector(doSomethingWithThis:);
Method m = class_getInstanceMethod(cls, my_sel);
// You could also use +[NSObject instanceMethodForSelector:] to get |m|,
// since |cls| is a kind of NSObject.
my_sel_t f = (my_sel_t)method_getImplementation(m);
BOOL result = f(nil, my_sel, #"Hello from an instanceless instance method invocation!");
NSLog(#"result: %d", (int)result);
return EXIT_SUCCESS;
}
You could get it to work even if the instance method accesses instance variables by allocating memory for it to work with (using either +alloc or class_getInstanceSize() plus malloc()) and passing a pointer to that memory as the first id argument to the implementation instead of nil.
While this is entertaining as an exercise, I can't think of a good reason to not just instantiate the class and use the standard messaging syntax and compiler support. In fact, the only reason we couldn't just do [(Foo *)nil doSomethingWithThis:#"BOO!"] here is that objc_msgSend() special-cases messages to nil with the result that NO is returned and nothing happens.