How can I call a method written in class1 to class2? - c

I have class1.m . I declared a method and written in it. Now i need to call it into another class. How can I make it? Can we use extern for it like we use for variables.
Thank you.

You should separate your declaration and definition, and place the declaration for class1 in class1.h. Then, you should include class1.h using #import "class1.h" in your source file for class2. Within class2, you can instantiate and use class1 as follows:
class1* instance_of_class1 = [[class1 alloc] init];
[class1 invokeMyMethod];
When you are done using your instance, be sure to decrement the reference count via release as in:
[instance_of_class1 release];
instance_of_class1 = nil;

I highly recommend reading Apple's Objective-C Programming Guide which will cover the fundamentals you need to know.

Related

Ruby C Extension using Singleton

I only wanted to allow one instance of my C extension class to be made, so I wanted to include the singleton module.
void Init_mousetest() {
VALUE mouseclass = rb_define_class("MyMouse",rb_cObject);
rb_require("singleton");
VALUE singletonmodule = rb_const_get(rb_cObject,rb_intern("Singleton"));
rb_include_module(mouseclass,singletonmodule);
rb_funcall(singletonmodule,rb_intern("included"),1,mouseclass);
### ^ Why do I need this line here?
rb_define_method(mouseclass,"run",method_run,0);
rb_define_method(mouseclass,"spawn",method_spawn,0);
rb_define_method(mouseclass,"stop",method_stop,0);
}
As I understand it, what that line does is the same as Singleton.included(MyMouse), but if I try to invoke that, I get
irb(main):006:0> Singleton.included(MyMouse)
NoMethodError: private method `included' called for Singleton:Module
from (irb):6
from C:/Ruby19/bin/irb:12:in `<main>'
Why does rb_include_module behave differently than I would expect it to? Also any tangential discussions/explanations or related articles are appreciated. Ruby beginner here.
Also it seems like I could have just kept my extension as simple as possible and just hack some kind of interface later on to ensure I only allow one instance. Or just put my mouse related methods into a module... Any of that make sense?
according to http://www.groupsrv.com/computers/about105620.html the rb_include_module() is actually just Module#append_features.
Apparently Module#include calls Module#append_features and Module#included. So in our C code we must also call included. Since clearly something important happens there.

A std::tr1::shared_ptr for Objective C++ on iPhone?

I am mostly a C++ developer, recently I am writing iPhone applications.
The memory management on iPhone is OK to me, due to resource limitation, it's encouraged to use reference counters rather than deep copy.
One annoying thing is I have to manage the reference counters by myself: alloc means counter = 1; retain means counter++, release means counter--
I wish to write a shared_ptr like class for Cocoa Touch, so I rarely have to manually manipulate the reference counters by myself.
I doubt if there's any existing code for that, and I'd like to hear some advices, today is the 5th day since I started to learn objective c
Thanks.
As long as you learn the memory management rules first, there is no real problem with shared_ptr - it can help you in C++ contexts but doesn't let the ownership questions magically disappear.
shared_ptr supports a custom deallocator so the following:
#interface A : NSObject
- (void)f;
#end
#implementation A
- (void)dealloc { NSLog(#"bye"); [super dealloc]; }
- (void)f { NSLog(#"moo"); }
#end
void my_dealloc(id p) {
[p release];
}
// ...
{
shared_ptr<A> p([[A alloc] init], my_dealloc);
[p.get() f];
}
... outputs:
moo
bye
... as expected.
If you want you can hide the deallocator from the user using a helper function, e.g.:
template<class T> shared_ptr<T> make_objc_ptr(T* t) {
return shared_ptr<T>(t, my_dealloc);
}
shared_ptr<A> p = make_objc_ptr<A>([[A alloc] init]);
You forgot case 4
[4] you need to pass a pointer to an object out of a method as the return value.
This is where you need -autorelease.
I suggest you read the memory management rules and write some real code before you attempt this little project so that you can get a feel of how memory management is supposed to work.
Automatic reference counting, coming in iOS 5, will effectively make any pointer to an objective-c object act like a smart pointer. Retain/release calls will be synthesized by the compiler on assign and deallocation, unless you explicitly declare a reference to be weak, in which case they'll be automatically zeroed out when the object is deallocated.
My advice is to wait a couple of months for that. You might be able to put together something similar in the meantime, but I'd recommend against it. For one thing, it'll be ugly. Example:
smart_ptr<id> array = make_smart_ptr( [NSMutableArray array] );
NSUInteger count = [array count]; // won't work.
count = [array.get() count]; // works, but yuck.
[array.get() setArray: anotherArray.get()]; // even more yuck.
Also, if your headers are full of c++ classes, you'll have to compile your entire project in objective-c++, which may cause you problems as objective-c++ isn't 100% compatible with objective-c code, and not all third-party frameworks will work properly with it. And forget about sharing your code with anyone else.
It might be an interesting excercise to make something like this work, but you won't want to actually use it. And watch out for the temptation to recreate your favourite bits of C++ in Objective-C. The languages are very different, and you could spend a lot of time doing that, which is time not spent learning all the great stuff you can do in Objective-C that you can't do in C++.
Resource management in Cocoa can be tricky: some API calls automatically retain a reference and some don't, some return an autoreleased object, some a retained object. By shielding this in a shared_ptr class, you'll more likely to make mistakes. My advice is to first take the "normal" Cocoa route until you're fairly experienced.
Have you looked into [object autorelease]? Perhaps that would make things a bit easier.

Naming convention in Objective C /C , start with "_"?

Something I see ppl define the variable like this:
b2World *_world;
b2Body *_body;
CCSprite *_ball;
instead of
b2World *world;
b2Body *body;
CCSprite *ball;
I familiar with the second one, but not the first one. So, I checked the Wikipedia about naming convention:
Names beginning with double underscore
or an underscore and a capital letter
are reserved for implementation
(compiler, standard library) and
should not be used (e.g. __reserved or
_Reserved).
So, is that any special meaning which is start with "_"?
The code I saw which using "_" to begin is here:
http://www.raywenderlich.com/457/intro-to-box2d-with-cocos2d-tutorial-bouncing-balls
The wiki page.
There's a long-standing convention among some Objective-C developers to prefix instance variables with an underscore. It can be helpful in several ways: one, it makes it easier to spot instance variables in a .m file; two, it relieves developers of having to come up with creative names for method parameters to avoid colliding with instance variable names; and three, as others have noted, it indicates that the instance variables are private, and therefore shouldn't be accessed willy nilly throughout the code.
In fact, I'd argue for avoiding accessing instance variables directly in methods other than accessors (getters and setters), -dealloc, and -init.... Not that you should never, ever use them anywhere else, but you should at least give it some thought before using an instance variable directly in other methods.
It's really really helpful, but most people don't know why, and that's a shame.
Apple uses underscores to separate the way other objects access a particular object's variables, and the way a particular object access its own variables.
Now this may sound a little bit strange, but imagine the following: You probably all recognize the following compiler warning
.h
#property (nonatomic, retain, readonly) UITableView *tableView;
.m
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return [self loadSomethingElseForTableView:tableView];
}
This will result in a compiler warning, because it does not know wether you reference to the local variable "tableView", or the instance variable.
Therefore, Apple recommends you to add the following to the top of your #implementation.
#synthesize tableView = _tableView;
Now, when you reference to _tableView, the compiler knows that you mean the instance variable, and not the local one.
Also, this makes it a lot easier to understand the Garbage Collection in Obj-C, and to prevent making common mistakes.
For example, when doing the following:
#property (nonatomic, retain, readonly) NSString *title;
- (id)initWithTitle:(NSString *)title {
if ((self = [super init])) {
self.title = title; // Is not possible, since it's read only.
title = title; // Is not possible, since it's the same (local) variable.
// Changing the method to initWithTitle:(NSString *)aTitle;
title = aTitle;
}
return self;
}
Now, since you do not use the default setter (actually, you can't, because it's read-only) you need to retain the variable yourself.
This is a lot easier to remember when you give every instance variable a prefix (so you know you need to retain it yourself).
So, basically, it's important to understand the difference between self.variable and (_)variable. (that is: self.variable maps to [self setVariable:...] and variable maps directly to your pointer.
Furthermore, when you add it as a private variable, like this:
#interface TSSomeObject : NSObject {
#private
NSString *_privateTitle;
}
#end
The underscore prefix isn't really necessary, unless you may encounter local variables that have the same name. Besides that, again, it's also an easy way to remind you that it's a local pointer and that you need to retain (and release) the variable when you assign it to your object.
What is wrong is to create a property with a underscore prefix, like this:
#property (nonatomic, retain) NSString *_title;
That's really wrong, and I'm not even gonna explain why ;)
So yes! You should really use underscore prefixes, it makes your code a lot easier to read, and to interpret by the compiler! In Xcode 4, Apple even added these #synthesizes to the default templates.
Usually they're used for variables that shouldn't be accessed outside the current file/module/namespace/whatever, in languages that don't support restricting access with something like a private keyword
https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/CodingGuidelines/Articles/NamingIvarsAndTypes.html#//apple_ref/doc/uid/20001284-1001757
Both by convention and recommendation in the above document, you should prefix ivars with an underscore.
Admittedly, it is in reference to explicitly set ivars for properties.
But the usage is the same, to indicate the usage of an ivar wherever it is seen.
I am however open to the possibility, that in that context, the use of an underscore prefixed ivar could signal to the user that they are doing something wrong. Meanwhile a postfixed underscore could be used for pure ivars that are meant to be accessed directly.
This blog has some good thoughts from an experienced practitioner and it recommends using prefixed underscores.
http://blog.bignerdranch.com/463-a-motivation-for-ivar-decorations/
Wether you choose to use prefixed underscores to decorate your own ivars, there is at least some evidence that some kind of decoration will help you avoid bugs. And prefix'd underscores are the most common decoration.
Apple reserves names beginning with underscore for its own private ivars and methods. In Objective-C on any Apple platform, it is recommended that you do not prefix your identifiers with an underscore.
http://developer.apple.com/mac/library/documentation/Cocoa/Conceptual/CodingGuidelines/Articles/NamingMethods.html

What is significance of static keyword in Java and in C++?

What is the importance of Static keyword in Java and in C++ and how it's functionality differ in both programming languages ?
Maybe this link will give you a better idea: http://www.pp.rhul.ac.uk/~george/PH2150/html/node48.html
It has a visual diagram that may make it easier to understand.
There are 2 meanings for static. The first if you have a static variable, this means there is only 1 instance of this variable. It works pretty much the same in all programming languages with the keyword.
A static function is a function that can be called, even if the class it resides in is not instantiated. Static functions are necessary in C# and Java because you cant declare functions in these languages which have no encompassing class.
in C++, you can declare functions in the global namespace. In this language, static functions are used to denote that a function belongs to the class, but you dont have to instantiate the class to use the function. You could use a static function to access private variables of the class. Also note that in C++, static functions have a known memory address, so you can use function pointers to point to them without instantiating the class.
For Java, Understanding Instance and Class Members is a good place to start.
For C++, Microsoft has a reference on the static keyword.
There are many readily available programming language resources that will help you understand what the static keyword means. The above are two of them that I found with a quick Google search.
Use static for fields and methods that can only have one instance. That means they are not relevant to instances of a class, but to the class itself. For example the main thread (public static void main).
It works the same way in both languages. I assume you know what's object-oriented programming, and what's the difference between classes and objects/instances. So, if you mark a method or variable as "static", it operates on a class level, not instance level. All objects/instances share the same value of the "static" variable.

Obj-C: C functions declared inside or outside #implementation block, what's the difference?

what's the difference between a C function (static or not) declared inside or outside the implementation block (#implementation ... #end) of a Objective-C class?
is this specially true?:
If you need to poke inside of the object directly, you can put this function inside of the #implementation block of your class, and then you can access instance variables with the C arrow operator. But that’s kind of naughty, so to preserve your Purity of Essence you should be using method calls on your object. End of Sermon. Here’s the evil:
#implementation OblateSphereoid
void drawEggThunk (DrawingContext *context, Rect areaToDraw, void *userData)
{
BWOblateSphereoid *dealie = (BWOblateSphereoid *)userData;
dealie->_frognatz = [NSColor plaidColor];
// and more stuff.
} // drawEggThunk
...
#end // OblateSphereoid
can i access instance variables of my class within functions (declared in the same class) in this way?
While this is legal, I don't understand why it's required in the kind of case you've described (and it is an ugly solution). Why can't you just call:
[dealie setFrognatz:[NSColor plaidColor]];
If you don't usually provide a -setFrognatz:, just make it a private method by declaring it inside the .m, but above this function definition. (It doesn't actually matter if it's in the #implementation block in this case.)
#interface BWOblateSphereoid ()
- (void)setFrognatz:(NSColor *)acolor
#end
#implementation OblateSphereoid
void drawEggThunk (DrawingContext *context, Rect areaToDraw, void *userData)
{
BWOblateSphereoid *dealie = (BWOblateSphereoid *)userData;
[dealie setFrognatz:[NSColor plaidColor]];
// and more stuff.
} // drawEggThunk
...
#end // OblateSphereoid
There are a few places where -> notation can be helpful. The most critical is in implementing -copyWithZone: where it can be absolutely required (a requirement that really emphasizes why I hate any ObjC code that plays with raw memory like NSCopyObject() does). But I recommend against -> in most cases for the same reasons I always recommend accessors. Even in the case where you need to pass an ivar by reference to a C function (another common use of ->), I prefer using a temporary and then assigning it afterwards.
I consider the fact that ivars are not #private by default to be a bug in ObjC.... I put #private at the top of every #interface block and have avoided several nasty bugs that way.
BTW, your solution as written may be leaking an NSColor. Maybe it is, maybe it's not, but an accessor would be certain.
This will work fine if its inside your #implementation. I'd recommend you make it a normal method, but it works.
If you put it out of your implementation, you get this warning: Warning: instance variable '' is #protected; this will be a hard error in the future. You can avoid this error by putting a #public before your iVar in the header... like so:
#public
int myInt;
That allows you to access the variables like a C (pointer) Struct wherever the object appears without warning.
So its doable, not recommended though!!!

Resources