Objective-C language
Objective-C is the primary language used to write Mac software. If you're comfortable with basic object-oriented concepts and the C language, Objective-C will make a lot of sense.
Calling Methods
[object method];
[object methodWithInput:input];
output = [object methodWithOutput];
output = [object methodWithInputAndOutput:input];
id myObject = [NSString string];
In this example, it's obvious the object type will be an NSString, so we can change the type:
NSString* myString = [NSString string];
Notice that there's a asterisk to the right of the object type. All Objective-C object variables are pointers types. The id type is predefined as a pointer type, so there's no need to add the asterisk.
Nested Messages
function1 ( function2() );
[NSString stringWithFormat:[prefs format]];
Multi-Input Methods
-(BOOL)writeToFile:(NSString *)path atomically:(BOOL)useAuxiliaryFile;
BOOL result = [myData writeToFile:@"/tmp/log.txt" atomically:NO];
Accessors
[photo setCaption:@"Day at the Beach"]; output = [photo caption];
Whenever you see code inside square brackets, you are sending a message to an object or a class.
Dot Syntax
photo.caption = @"Day at the Beach";
output = photo.caption;
Creating Objects
NSString* myString = [NSString string];
NSString* myString = [[NSString alloc] init];
The second piece is a call to init on the new object. The init implementation usually does basic setup, such as creating instance variables. The details of that are unknown to you as a client of the class.
In some cases, you may use a different version of init which takes input:
NSNumber* value = [[NSNumber alloc] initWithFloat:1.0];
Basic Memory Management
However, you may not always be working with an environment that supports garbage collection. In that case, you need to know a few basic concepts.
If you create an object using the manual alloc style, you need to releasethe object later. You should not manually release an autoreleased object because your application will crash if you do.
Here are two examples:
// string1 will be released automatically
NSString* string1 = [NSString string];
// must release this when done
NSString* string2 = [[NSString alloc] init];
[string2 release];
There's more to learn about memory management, but it will make more sense after we look at a few more concepts.
Designing a Class Interface
The class interface is usually stored in the ClassName.h file, and defines instance variables and public methods.
The implementation is in the ClassName.m file and contains the actual code for these methods. It also often defines private methods that aren't available to clients of the class.
Here's what an interface file looks like. The class is called Photo, so the file is named Photo.h:
#import <Cocoa/Cocoa.h> @interface Photo : NSObject {
NSString* caption;
NSString* photographer;
} @end
The @interface says that this is a declaration of the class Photo. The colon specifies the superclass, which is NSObject.
Inside the curly brackets, there are two instance variables: caption and photographer. Both are NSStrings, but they could be any object type, including id.
Finally, the @end symbol ends the class declaration.
Add Methods
#import <Cocoa/Cocoa.h> @interface Photo : NSObject {
NSString* caption;
NSString* photographer;
} - caption;
- photographer; @end
By default, the compiler assumes a method returns an id object, and that all input values are id. The above code is technically correct, but it's unusual. Let's add specific types for the return values:
#import <Cocoa/Cocoa.h> @interface Photo : NSObject {
NSString* caption;
NSString* photographer;
} - (NSString*) caption;
- (NSString*) photographer; @end
#import <Cocoa/Cocoa.h> @interface Photo : NSObject {
NSString* caption;
NSString* photographer;
}
- (NSString*) caption;
- (NSString*) photographer; - (void) setCaption: (NSString*)input;
- (void) setPhotographer: (NSString*)input; @end
Class Implementation
#import "Photo.h" @implementation Photo - (NSString*) caption {
return caption;
} - (NSString*) photographer {
return photographer;
} @end
The getters should look very familiar if you've ever written code, so let's move on to the setters, which need a bit more explanation:
- (void) setCaption: (NSString*)input
{
[caption autorelease];
caption = [input retain];
} - (void) setPhotographer: (NSString*)input
{
[photographer autorelease];
photographer = [input retain];
}
- (void) setCaption: (NSString*)input {
caption = input;
}
There are actually two ways to free a reference to an object: release andautorelease. The standard release will remove the reference immediately. The autorelease method will release it sometime soon, but it will definitely stay around until the end of the current function (unless you add custom code to specifically change this).
The autorelease method is safer inside a setter because the variables for the new and old values could point to the same object. You wouldn't want to immediately release an object which you're about to retain.
This may seem confusing right now, but it will make more sense as you progress. You don't need to understand it all yet.
Init
- (id) init
{
if ( self = [super init] )
{
[self setCaption:@"Default Caption"];
[self setPhotographer:@"Default Photographer"];
}
return self;
}
This essentially just asks the superclass to do its own initialization. The ifstatement is verifying that the initialization was successful before trying to set default values.
Dealloc
- (void) dealloc
{
[caption release];
[photographer release];
[super dealloc];
}
The last line is very important. We have to send the message
[super dealloc] to ask the superclass to do its cleanup. If we don't do this, the object will not be removed, which is a memory leak.
The dealloc method is not called on objects if garbage collection is enabled. Instead, you implement the finalize method.
More on Memory Management
In simplest terms, you alloc an object, maybe retain it at some point, then send one release for each alloc/retain you sent. So if you used alloc once and then retain once, you need to release twice.
1. To keep it as an instance variable
2. To use temporarily for single use inside a function
In most cases, the setter for an instance variable should just autoreleasethe old object, and retain the new one. You then just make sure to release it in dealloc as well.
So the only real work is managing local references inside a function. And there's only one rule: if you create an object with alloc or copy, send it a release or autorelease message at the end of the function. If you create an object any other way, do nothing.
Here's the first case, managing an instance variable:
- (void) setTotalAmount: (NSNumber*)input
{
[totalAmount autorelease];
totalAmount = [input retain];
} - (void) dealloc
{
[totalAmount release];
[super dealloc];
}
NSNumber* value1 = [[NSNumber alloc] initWithFloat:8.75];
NSNumber* value2 = [NSNumber numberWithFloat:14.78]; // only release value1, not value2
[value1 release];
And here's a combo: using a local reference to set an object as an instance variable:
NSNumber* value1 = [[NSNumber alloc] initWithFloat:8.75];
[self setTotal:value1]; NSNumber* value2 = [NSNumber numberWithFloat:14.78];
[self setTotal:value2]; [value1 release];
If you understand this, you understand 90% of what you will ever need to know about Objective-C memory management.
Logging
NSLog ( @"The current date and time is: %@", [NSDate date] );
Properties
Properties are a feature in Objective-C that allow us to automatically generate accessors, and also have some other side benefits. Let's convert the Photo class to use properties.
Here's what it looked like before:
#import <Cocoa/Cocoa.h> @interface Photo : NSObject {
NSString* caption;
NSString* photographer;
}
- (NSString*) caption;
- (NSString*) photographer; - (void) setCaption: (NSString*)input;
- (void) setPhotographer: (NSString*)input; @end
#import <Cocoa/Cocoa.h> @interface Photo : NSObject {
NSString* caption;
NSString* photographer;
}
@property (retain) NSString* caption;
@property (retain) NSString* photographer; @end
Now let's take a look at the implementation of the class:
#import "Photo.h" @implementation Photo @synthesize caption;
@synthesize photographer; - (void) dealloc
{
[caption release];
[photographer release];
[super dealloc];
} @end
Accessors will only be generated if they don't already exist, so feel free to specify @synthesize for a property, then implement your custom getter or setter if you want. The compiler will fill in whichever method is missing.
There are many other options for the property declarations, but those are outside of the scope of this tutorial.
Calling Methods on Nil
This technique used by the frameworks in a number of different ways, but the main thing it means to you right now that you usually don't need to check for nil before calling a method on an object. If you call a method on nil that returns an object, you will get nil as a return value.
We can also use this to improve our dealloc method slightly:
- (void) dealloc
{
self.caption = nil;
self.photographer = nil;
[super dealloc];
}
Note that we're using the self.<var> syntax here, which means we're using the setter and picking up the memory management for free. If we just directly set the value like this, there would be a memory leak:
// incorrect. causes a memory leak.
// use self.caption to go through setter
caption = nil;
Categories
This is particularly useful because you can add methods to built-in objects. If you want to add a method to all instances of NSString in your application, you just add a category. There's no need to get everything to use a custom subclass.
For example, if I wanted to add a method to NSString to determine if the contents is a URL, it would look like this:
#import <Cocoa/Cocoa.h> @interface NSString (Utilities)
- (BOOL) isURL;
@end
Here's the implementation. Keep in mind this is not a good implementation of URL detection. We're just trying to get the concept of categories across:
#import "NSString-Utilities.h" @implementation NSString (Utilities) - (BOOL) isURL
{
if ( [self hasPrefix:@"http://"] )
return YES;
else
return NO;
} @end
NSString* string1 = @"http://pixar.com/";
NSString* string2 = @"Pixar"; if ( [string1 isURL] )
NSLog (@"string1 is a URL"); if ( [string2 isURL] )
NSLog (@"string2 is a URL");
Remember, when you make changes to a class using a category, it affects all instances of that class throughout the application.
最新文章
- 安卓(android)之实现断点下载功能
- 移动端bug~~移动端:active伪类无效的解决方法【移动端 :active样式无效】
- 运用Fluxion高效破解WiFi密码
- Java基础(33):StringBuilder的方法与应用实例(String相关类)
- No module ata_piix found的解决方法
- bug_ _java.lang.RuntimeException: Unable to start activity ComponentInfo{包名/类名}
- FPGA保留信号的语句
- 三维偏序-二维LIS
- codeforces #330 div2
- 从源码看Android中sqlite是怎么通过cursorwindow读DB的
- jQuery Mobile 自定义按钮图标
- 让Chrome看不了WWDC直播的HLS技术详解
- 【转】python入门指引
- 浅析GDAL库C#版本支持中文路径问题
- 解决 django 博客归档 “Are time zone definitions for your database and pytz installed?”的错误
- tomcat 热部署、热加载 精析
- flask factory
- C# 绘制图表(柱状图,线性图,饼状图)
- Python实现屏蔽敏感词
- JMeter提取和重用作为变量 - 具有更多提取器
热门文章
- 如何使用Psyco为你的Python程序提速
- Markdown Reader 插件改造
- Win10+CUDA9.0+cudnn7.1安装
- nohup 命令 print 不能实时输出至 nohup.out
- Python_中__init__和__new__的异同
- 使用IntelliJ IDEA配置Tomcat(入门)
- 【Hadoop】HDFS笔记(二):HDFS的HA机制和Federation机制
- ThinkPHP3.2.3中,配置文件里配置项的读取
- 使用命令把类打成jar包
- C#操作cmd