Lesson 2 Writing Classes

Familiarize yourself with OC syntax. Write some classes and properties from scratch

In OC, every class is associated with two files, a header file and an implementation file. The header file represents the public interface and the implementation file holds method implementations as well as any properties we'd like to be private.



1.Declare a house class with 3 properties:

Swift Version
import Foundation

class house: NSObject {
    var address = String()
    var numberOfBedrooms = Int()
    var hasHotTub: Bool = false
}

OC Version
#import <Foundation/Foundation.h>

@interface House : NSObject


@property (nonatomic) NSString *address;
@property (nonatomic) int numberOfBedrooms;
@property (nonatomic) BOOL hasHotTub;

@end

說明:
@interface: 聲明一個class永部,要在前面加上@interface關(guān)鍵字媳荒;
@property:聲明屬性跳夭,要在前面加上@property關(guān)鍵字;
*address:星符號指明一個指針指向address搏存;
Nonatomic/Atomic:Nonatomic is a property attribute. Properties can be either atomic or nonatomic; this distinction relates to how properties are handled in multithreading. It is beyond the scope of this course to get into the specifics of the difference, but the vast majority of properties you will use will be nonatomic. The default is atomic, so you need to write “nonatomic” almost every time you declare a property.


2.在main.m文件中

#import <Foundation/Foundation.h>
#import "House.h"

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        House *myHouse = [[House alloc] init];
        NSLog(@"%@", myHouse);
    }
    return 0;
}

說明:
#import "House.h":要先import
[[House alloc] init]:Every time you create an object, you type alloc, which allocates some memory space and then init to initialize the object instance. alloc and init are always written together.


3.Syntax of method definitions

-(returnType)methodName: (parameter Type*)parameterName {
    body;
}
// House.m
#import "House.h"

@interface House()

@property (nonatomic, readwrite) int numberOfBedrooms;

@end

@implementation House
-(instancetype)initWithAddress: (NSString*)address {
    self = [super init];
    if(self) {
        _address = [address copy];
        _numberOfBedrooms = 2;
        _hasHotTub = false;
        
    }
    return self;
}
@end

說明:
self: First of all, what is self? You saw self from time to time in Swift, but in Objective-C its use is much more widespread. Self is a pointer to the object at hand. When you are writing code inside of a class, self is a pointer to an object of that class. Self is a pointer to the object at hand.
Second of all, what's an instance variable? An instance variable is what lies underneath a property. The word “property” technically refers to an instance variable's accessor methods, the getter and the setter that are automatically created when a property is declared. The thing itself, the address, in this case, is an instance variable. We actually almost never interact directly with instance variables. In fact, it's not recommended that you interact directly with instance variables outside of custom initializers.
:Every statement in Objective-C must end with a semicolon.


Quiz1:Create an Objective-C class with accompanying header file. The class will represent a book, and should have a title, author, and a year of publication. Be sure to provide a designated initializer.

// Book.h

@interface Book : NSObject

@property (nonatomic) NSString *title;
@property (nonatomic) NSString *author;
@property (nonatomic) int yearOfPublication;

-(instancetype)initWithTitle:(NSString*)title
                      author:(NSString*)author
                        year:(int)year;

@end

// Book.m

@implementation Book

-(instancetype)initWithTitle:(NSString*)title
                      author:(NSString*)author
                        year:(int)year {
    self = [super init];
    if(self) {
        _title = title;
        _author = author;
        _yearOfPublication = year;
    }

    return self;
}

@end    

4.Enum in OC

Enum definitions go at the top of your header file. The preferred way to create an enum is using the NS_ENUM macro, where NSInterger is the enum type and Direction is the enum name. All enums in OC are of type NSInteger.

// Bedroom.h
#import <Foundation/Foundation.h>

typedef NS_ENUM(NSInteger, Direction) {
    North,
    South,
    East,
    West
};

NS_ASSUME_NONNULL_BEGIN

@interface Bedroom : NSObject
@property (nonatomic) BOOL privatePath;
@property (nonatomic) Direction directionWindowFaces;

@end

NS_ASSUME_NONNULL_END

Important!---Use weak reference for: 1.delegate 2.subviews of the main view

More about memory cycle:
Apple's explanation of object ownership
An example of a retain cycle from stack overflow
Why we use weak pointers for delegation, from stack overflow
Debugging memory cycles: four likely culprits
Using Instruments to find memory leaks

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市矢洲,隨后出現(xiàn)的幾起案子璧眠,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 218,546評論 6 507
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件责静,死亡現(xiàn)場離奇詭異袁滥,居然都是意外死亡,警方通過查閱死者的電腦和手機灾螃,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,224評論 3 395
  • 文/潘曉璐 我一進店門呻拌,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人睦焕,你說我怎么就攤上這事藐握。” “怎么了垃喊?”我有些...
    開封第一講書人閱讀 164,911評論 0 354
  • 文/不壞的土叔 我叫張陵猾普,是天一觀的道長。 經(jīng)常有香客問我本谜,道長初家,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,737評論 1 294
  • 正文 為了忘掉前任乌助,我火速辦了婚禮溜在,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘他托。我一直安慰自己掖肋,他們只是感情好,可當我...
    茶點故事閱讀 67,753評論 6 392
  • 文/花漫 我一把揭開白布赏参。 她就那樣靜靜地躺著志笼,像睡著了一般。 火紅的嫁衣襯著肌膚如雪把篓。 梳的紋絲不亂的頭發(fā)上纫溃,一...
    開封第一講書人閱讀 51,598評論 1 305
  • 那天,我揣著相機與錄音韧掩,去河邊找鬼紊浩。 笑死,一個胖子當著我的面吹牛疗锐,可吹牛的內(nèi)容都是我干的坊谁。 我是一名探鬼主播,決...
    沈念sama閱讀 40,338評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼窒悔,長吁一口氣:“原來是場噩夢啊……” “哼呜袁!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起简珠,我...
    開封第一講書人閱讀 39,249評論 0 276
  • 序言:老撾萬榮一對情侶失蹤阶界,失蹤者是張志新(化名)和其女友劉穎虹钮,沒想到半個月后,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體膘融,經(jīng)...
    沈念sama閱讀 45,696評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡芙粱,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,888評論 3 336
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了氧映。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片春畔。...
    茶點故事閱讀 40,013評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖岛都,靈堂內(nèi)的尸體忽然破棺而出律姨,到底是詐尸還是另有隱情,我是刑警寧澤臼疫,帶...
    沈念sama閱讀 35,731評論 5 346
  • 正文 年R本政府宣布择份,位于F島的核電站,受9級特大地震影響烫堤,放射性物質(zhì)發(fā)生泄漏荣赶。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 41,348評論 3 330
  • 文/蒙蒙 一鸽斟、第九天 我趴在偏房一處隱蔽的房頂上張望拔创。 院中可真熱鬧,春花似錦富蓄、人聲如沸剩燥。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,929評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽晒他。三九已至笨腥,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間敞曹,已是汗流浹背胜卤。 一陣腳步聲響...
    開封第一講書人閱讀 33,048評論 1 270
  • 我被黑心中介騙來泰國打工疆导, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人葛躏。 一個月前我還...
    沈念sama閱讀 48,203評論 3 370
  • 正文 我出身青樓澈段,卻偏偏與公主長得像,于是被迫代替她去往敵國和親舰攒。 傳聞我的和親對象是個殘疾皇子败富,可洞房花燭夜當晚...
    茶點故事閱讀 44,960評論 2 355