Objective C custom class methods not being called - objective-c

So I have this custom class with just a test method that does nslog. I am going to reuse this method many times in my app. The interface looks like this.
#interface TestViewController: UIViewController { CMImageMover * imageMover }
Then in the view did load I:
imageMover = [[CmImageMover alloc] init];
If I do:
[imageMover testMethod];
Right after the alloc and init it works in the viewDidLoad function but if I call it again from another function in the view controller nothing works and the class method does not get called.
What am I doing wrong here. Every other var I declare like NSArray/NSTimer, I do the say way and I am able to access and use it throughout my controller.

When you say "if I call it again from another function in the view controller nothing works" then first thing to check is what you are sending the testMethod. It could be nil, in which case nothing will happen. In objective C sending a message to nil does nothing. Add an NSLog to find out, e.g.
NSLog(#"imageMover object is: %#", imageOver);
[imageMover testMethod];
If the NSLog shows it is nil - or something crazy - then follow up what you are doing with the imageMover ivar.
You mention a class method in your question, but don't refer to it in your code snippets.
If you have defined testMethod as a class method it will, of course, fail if you send that message to an instance. (And it will fail noisily.) A class method would be introduced like this:
+ (void) testMethod
{
NSLog(#"CMImageMover testMethod called on Class");
}
An instance method would be introduced like this:
- (void) testMethod
{
NSLog(#"testMethod called on an instance of CMImageMover");
}
Apologies if this is all screamingly obvious to you and missing the point of the question. It's not that clear from your question where the issue lies.

Related

Why doesn't this method let me reference anything?

I recently created a method that can be called from other classes, this is my code.
In the ViewController1.h
+ (void)updateName:(id)sender;
In the ViewController1.m
+ (void)updateName:(id)sender {
}
The method is calling and working which is good however I have another method in the ViewController1.m file which is
-(void)updateString {
NSLog(#"IT WORKED");
}
However, I try to call it in my updateName method like this:
+ (void)updateName:(id)sender {
[self updateString];
}
But I get an error saying "no known class method for selector 'updateString' " Can anyone tell why is this happening and how I can call this method? Thanks.
The + in front of the method denotes a class method i.e. you don't need to create a new instance of ViewController1 in order to call the method. Where as [self updateString] is an instance method i.e. you need to create a new instance of the class in order to perform it. The problem here is the difference in scope. See below:
Inside another class:
[ViewController1 updateName:SOMETHING];
vs
ViewController1 *newViewController1 = [[ViewController1 alloc] init];
[newViewController1 updateString];
EDIT
If you want to call that method from that class you can do this?
+ (void)updateName:(id)sender {
[ViewController1 updateString];
}
But that won't be able to reference or update any class properties etc.. So from the names of your methods, this is likely not going to solve your problem.
Does that make sense ?
You're doing something odd but to fix your problem simply replace the - with + in front of your method name.

Objective-C iOS callback function between classes

I'm new to iPhone application development, but I seem to have somewhat managed so far (learning as I go).. however, I've run in to an issue I can't figure out. Here's the scenario:
I have an extension class called CoreAPI which I have my network functions inside. I have a function called "Login" inside CoreAPI which makes a request to a server, gets the 0 or 1 response and returns true or false. I had this working perfectly with Synchronous requests, but now I need to make everything asynchronous.
So, below is what I'm trying to do.. this is not working with the error along the lines of "Object of type ID has no method loginCallback"
loginViewController.m
- (void) login {
CoreAPI APIObject = [[CoreAPI alloc] init];
[APIObject login:self];
}
- (void) loginCallback {
NSLog(#"It called back.");
}
CoreAPI.m
- (void)login:(id)sender {
[sender loginCallback];
}
Thanks, and please let me know if I have missed any details needed to help me.
I'm seeing a couple problems. First, I'm guessing you don't provide visibility of the loginCallback function to CoreAPI.m. You should be able to send any message to an id type, so long as it's defined for a known type.
However, I'd recommend using a completion block in this case. Here's what that could look like:
(in CoreAPI.h)
- (void)login:(void (^)(void))completed;
(in CoreAPI.m)
- (void)login:(void (^)(void))completed {
// Login code
if (completed) completed();
}
Calling it would look like:
CoreAPI APIObject = [[CoreAPI alloc] init];
[APIObject login:^{
NSLog(#"It called back.");
}];
They have really goofy syntax, but blocks are really nice for this sort of thing. Hope this helped! Let me know if I didn't explain something clearly.
this should do the trick for you:
first, import loginViewController header inside CoreApi.m
#import "loginViewController.h"
Then, change login method to this:
- (void)login:(id)sender {
[(loginViewController*)sender loginCallback];
}
Or this:
- (void)login:(loginViewController*)sender {
[sender loginCallback];
}
Explanation: notice that your login method is receiving by parameter one object of type id . In objective C, id type means a reference to any Objective-C of unknow class. So, inside your login method, the compiler doesn't know that the sender is a instance of your loginViewController class, so it won't recognize loginViewController's methods.
To informations about this, please read: Objective-C: difference between id and void *
Notice that I only focused in remove your actual error. You should have to do more things in order to accomplish your code to run asynchronous.
In order to perform a better callback, please look for delegates or blocks (like in oltman's answer).
To run things in background, look for CDG : http://developer.apple.com/library/ios/#DOCUMENTATION/General/Conceptual/ConcurrencyProgrammingGuide/OperationQueues/OperationQueues.html

setStringValue with void method

I have a button (IBAction), when I click the button a label will change (setStringValue).
Works perfectly.
Is there a way for changing a label (setStringValue) with a (void) method, so a method that is not an IBAction. Because if I call the method nothing happens? The code is illustrated below.
//IBAction method, label is changed to setLabelMethod, works perfect.
-(IBAction)setLabel:(id)sender{
[labelA setStringValue:#"Works!"];
ClassName *MyClass = [[ClassName alloc]init];
[MyClass methodSetLabel]
}
//void method, nothing happens
-(void)methodSetLabel{
[labelB setStringValue:#"Works!"];
}
What do I have to do to make this work?
Thanks!
IBAction methods are void. The reason nothing happens is different from what you think: it's not because the method is void, it's because the instance on which you call the method is wrong.
Your setLabel method creates a new instance of MyClass. That's not the class that has the real labelB displayed on your screen.
You need to call the method on the same object that owns the label and runs the setLabel: method. In Objective C this object is represented by a special variable called self. If you rewrite the method as follows
-(IBAction)setLabel:(id)sender{
[labelA setStringValue:#"Works!"];
[self methodSetLabel];
}
it should work.

iOS MVC - How to pass data from model to controller?

I did quite a bit of research on this, but I am having a mental block about my problem. I am working on Objective-C for an iOS app
Here's my set up:
The view controller gets a text from the view (user input), and passes that text to the MethodA of the model.
The MethodA in model works on the input text and gets an output (e.g. searches google for that text). It does the search using dispatch_async method which calls the selector to MethodB within model.
MethodB parses the output and puts all the results into a NSMutableArray
My Question Here: how do I pass that NSMutableArray back to view controller so I can show it on the view?
Sorry, if the answer to my question is very simple/obvious. I am new to Objective-C
Any time I want to do async processing and that stuff needs to get back into the UI somewhere, I do one of two things:
1. Use NSNotification to tell anyone who cares that the work is complete
2. Use a delegate property on the worker and a #protocol
1 NSNotification
The model object should document in it's .h file that it fires notifications when certain things happen; such as when a portion of the model has been updated. When the ViewController initializes the model object, have it set itself up as an observer of the documented notification, and implement a callback which updates the UI.
2 delegation and #protocol
Create a #protocol such as #protocol FooModelUpdateDelegate with a method properly named such as fooObjectDidUpdate:(Foo *)object;, and then the model class has a delegate property as id<FooModelUpdateDelegate> updateDelegate and the ViewController sets itself as that delegate, and I'm sure you can figure out the rest.
I guess passing along a delegate-object that respoons to a selector-method and calling this method with the processed data will be a good way to achieve the loosley coupled structure your program deserves. Are you familiar with this concept, or shall I dig up some code-samples for you?
UPDATE: Code samples
So, I would probably use the calling class, say MyViewController, to implement the callbackMethod, myCallbackMethod as follows:
-(void) myCallbakcMethod: NSMutableArray* array {
//DoWhatever with the returned data
}
The point is to get the result passed back to this method when the computation is finished.
So in your MyViewController where you call MethodA you pass along a reference to the delegate to handle the result, namly self.
//From this:
[MyModel methodA:param1]
//To:
[MyModel methodA:param1:self]
MyModels methodA and methodB would need to add a parameter (id)delegate and pass that along between the calls.
In methodB where the data myArray is ready, do the following call:
if([delegate respondsToSelector:#selector(myCallbackMethod:)]])
[observer performSelector:#selector(myCallbackMethod:) withObject:myArray];
In your view controller:
// your controller code
...
[myModel getSearchResult:searchKeyword receiver:self action:#selector(responseReceived:)];
}
- (void)responseReceived:(MyModel *)model
{
NSArray *searchResult = model.searchResult;
[model release], model = nil;
// some view actions, for instance update your table view
...
}
In your model:
...
- (id)getSearchResult:(NSString *)searchKeyword receiver:(id)aReceiver action:(SEL)receiverAction {
self.receiver = aReceiver;
self.action = receiverAction;
// some async actions
}
In async response receiver:
...
[self.receiver performSelector:self.action withObject:self];
}
Unless I'm misunderstanding your description it sounds like your "model" class is doing more than it should. In this case it's doing at least some of the work of your controller. My suggestion would be to fold methodA and methodB into the view controller (or another controller class). Method B could still set the NSMutableArray property of "model" instance, if that's essential (or skip that step if it's not).
-(void)methodA {
NSMutableArray *someArray = ...
[self methodB:someArray];
}
-(void)methodB:(NSMutableArray*)array {
NSLog(#"%#", array);
// do something with the array, like update the view
}
But if both are methods inside the view controller why not just update the view inside the method instead of passing it to another method?

Objective-C: How to check if a class gets extended by a category?

In Java, you can use instanceof to check if a class extends another class or implements an interface.
In Objective-C, you can use isKindOfClass to check if a class extends another class:
if ([myObject isKindOfClass:[AnClass class]]) { }
But how can I check if a class gets extended by a category?
EDIT 2
My code of the first EDIT was unfortunately a bit confusing and nonsensical, sorry! Now, here is my new code:
I'll explain the whole problem:
I've got a class ViewCustomerCreate thats extends UITableViewController. ViewCustomerCreate gets extended by the category ICheckBox. This is my code that doesn't work:
- (void)closeModalView {
UINavigationController *parent = (UINavigationController *)self.navigationController.parentViewController;
UIViewController *parentViewContr = parent.topViewController;
if ([parentViewContr isKindOfClass:[id<ICheckBox> class]]) { // ERROR-MESSAGE see below
id<ICheckBox> parent2 = (id<ICheckBox>)parentViewContr; // works fine :-)
[parent2 setSelectedElementId:checkedIndex]; // works fine :-)
}
[self.navigationController dismissModalViewControllerAnimated:YES];
}
The error message is: "error: 'id' is not an Objective-C class name or alias"
I think that I can't use isKindOfClass to check if a class gets extended by a category, isn't it?
PS: What do I want? I have a general modal view with checkboxes and if I close this view, the parent-view should get informed what the user choose.
EDIT 3
OMG, I confounded Category with Protocol!! Aaaaahhhhh ^^
THE SOLUTION:
if ([parentViewContr conformsToProtocol:#protocol(ICheckBox)]) {
There is no way to check if a class is extended by a category, but you can check whether or not an instance responds to a particular selector with:
- (BOOL)respondsToSelector:(SEL)sel;
In Objective-C you should worry less about what an object is, and worry more about what an object can do.
If it walks like a duck, sounds like a duck and looks like a duck, then it can probably fly, you know what I mean?
You should use this as such:
if ([myObject respondsToSelector:#selector(myMethod:)])
{
// do whatever you need to do
}
Just a quick note, since you mentioned Java interfaces. You can check if an object implements a protocol (similar to Java interfaces, but not exactly the same) by using:
- (BOOL)conformsToProtocol:(Protocol *)aProtocol;
If you have defined a category on UIViewController, there are no instances of UIViewController that it is not applied to. Hence, a runtime check does not make sense.
Let's look at your actual problem:
parent.setMySpecialValue = 1; // DOES NOT WORK :-(
What does "DOES NOT WORK" actually mean? Do you get a compiler error or a runtime error. If the former, there are a couple of possible issues to loo at:
You haven't included the header file containing the category in the source file that uses that method
It is a property that you have named incorrectly. If the property is called mySpecialValue, that line of code should read:
parent.mySpecialValue = 1;
or
[parent setMySpecialValue: 1];
As of now, categories cannot define instance variables, so having a synthesized property might be an issue, so that might also be your problem, but you need to give more information about what "DOES NOT WORK" means.