Reputation: 41
If I have something I want to do repeatedly in an Xcode iPhone app, how do I set it up and call it?
For example, if I wanted to do this simple line lots of times from lots of different places in an app: label1.text = @"Hello";
And then what if I wanted to call or perform it from lots of different apps: how would I convert it into my own library, so I can import all my common code?
(I'm a COBOL programmer trying to learn how to program for the iPhone in Xcode. COBOL seems so easy compared to Objective-C and XCode!)
Upvotes: 0
Views: 678
Reputation: 64428
For example, if I wanted to do this simple line lots of times from lots of different places in an app: label1.text = @"Hello";
Firstly, in every class where you want to run the line, you would have to have a reference to the label1 object. Since in this case, this is a interface element, the easiest way would be to set an outlet in your header and then connect it up in interface builder.
@interface MyController : UIViewController
{
IBOutlet UILabel *label1;
}
@property(nonatomic, retain) IBOutlet UILabel *label1;
@end
Every class instance that refers to the label instance must have an outlet pointing to it and then you have to wire the outlet to the proper label in interface builder. (You can also create the relationship programmatically but that is more complex.) This way when you set the text of the label in your code, the runtime knows what object to send the message to.
If you have a background in a procedural language like Cobol (shudder), you're going to have to change your thinking to one based on object-oriented program. Objective-C design is even more object dependent than other common OOP languages.
Upvotes: 0
Reputation: 35535
You can split off the reusable code into small functions and classes, and put them in their own separate header and source files. This is a simple step that will greatly help you clean up your code.
Eventually you can put these files into a separate Xcode library project. This will enable you link with that project from different applications. However, this is somewhat advanced, and it looks that you are very new to all this so you may want to focus on the basics first.
Upvotes: 1
Reputation: 75077
The thing to search for is "Static Library", that's what you want to create that would let people use your code as a library.
This site has a pretty good walkthrough:
http://blog.stormyprods.com/2008/11/using-static-libraries-with-iphone-sdk.html
If your code is simple enough, just publishing source files that other people can include in a project suffices.
Upvotes: 0