Learn Objective C(5)Programming with Objective-C - Working with Protocols and Values and Collections
5. Working with Protocols
Objective-C allows you to define protocols, which declare the methods expected to be used for a particular situation.
a. Defining a protocol
b. Mark a class interface as conforming to a protocol
5.1 Protocols Define Messaging Contracts
A protocol is used to declare methods and properties that are independent of any specific class.
@protocol ProtocolName
//list of methods and properties
@end
Think about a pie chart, number of segments, relative size of each segment, title of each segment.
@protocol ZJUPieChartViewDataSource
- (NSUInteger) numberOfSegments;
- (CGFloat) sizeOfSegmentAtIndex:(NSUInteger)segmentIndex;
- (NSString *)titleForSegmentAtIndex:(NSUInteger)segmentIndex;
@end
So the only thing the view class know is the id reference and protocol.
@interface ZJUPieChartView : UIView
@property (weak) id <ZJUPieChartViewDataSource> dataSource;
…snip...
@end
Objective-C uses angle brackets to indicate conformance to a protocol.
Protocols Can Have Optional Methods
It is also possible to specify optional methods in a protocol. We can use @optional directive like this
@optional
- (NSString *) titleForSegmentAtIndex: (NSUInteger) segmentIndex;
The optional directive applies to any methods that follow it, either until the end of the protocol definition, or until another directive is encountered, such as @required.
- (CGFlot) sizeOfSegmentAtIndex: (NSUInteger) segementIndex;
@optional
- (NSString *) titleForSegmentAtINdex: (NSUInteger) segmentIndex;
- (BOOL) shouldExplodeSegmentAtIndex: (NSUInteger) segmentIndex;
@required
- (UIColor *) colorForSegmentAtIndex: (NSUInteger) segmentIndex;
Check that Optional Methods Are Implemented at Runtime
We need to check the optional methods before we use them.
NSString *thisSegmentTitle;
if([self.dataSource respondsToSelector: @selector(titleForSegmentAtIndex:) ]){
thisSegmentTitle = [self.dataSource titleForSegmentAtIndex:index];
}
Protocols Inherit from Other Protocols
@protocol MyProtocol <NSObject>
…
@end
5.2 Conforming to Protocols
@interface MyClass : NSObject <MyProtocol>
…
@end
If we need a class to adopt multiple protocols, we specify them as a comma-separated list.
@interface MyClass : NSObject <MyProtocol, AnotherProtocol, YetAnotherProtocol>
…
@end
Cocoa and Cocoa Touch Define a Large Number of Protocols
NSTableView ------ NSTableViewDelegate
UITableView ------ UITableViewDelegate
5.3 Protocols Are Used for Anonymity
…snip...
6. Values and Collections
It is a superset of C, we can use any of the standard C scalar types like int, float and char in Objective-C.
If you plan to use NSArray or NSDictionary, we need to put NSValue, NSNumber, or NSString in the arrays.
6.1 Basic C Primitive Types Are Available in Objective-C
int someInteger = 42;
someInteger++;
Objective-C Defines Additional Primitive Types
BOOL ---- YES NO
USInteger --- building for a 32-bit environment, such as for iOS
USUInteger --- 64-bit environment, such as for OS X
It is best practice to use these platform-specific types as arguments or return values in method or function calls between application code and framework. For local variable, such as a counter in a loop.
C Structures Can Hold Primitive Values
…
6.2 Objects Can Represent Primitive Values
Strings Are Represented by Instances of the NSString Class
NSString *firstString = [[NSString alloc] initWithCString:"hello"
encoding:NSUTF8StringEncoding];
NSString *thirdString = @"hello";
NSString is immutable.
NSString *name = @"Carl";
name = [name stringByAppendingString:@"son"]; //return a new string object
NSMutableString *name = [NSMutableString stringWithString:@"John"];
[name appendString:@"ny"]; // same object with different value
NSString stringWithFormat:@"The magic number is %i", intNumber];
Numbers Are Represented by Instances of the NSNumber Class
NSNumber *magicNumber = [[NSNumber alloc] initWithInt:42];
NSNumber *longNumber = [[NSNumber alloc] initWithLong:42l];
NSNumber *boolNumber = [[NSNumber alloc] initWithBOOL:YES];
NSNumber *someChar = [NSNumber numberWithChar:'T'];
We can init NSNumber with all these primitive types, char, double, float, int, long, short, BOOL.
NSNumber *magicNumber = @42;
NSNumber *unsignedNumber = @42u;
NSNumber *longNumber = @42l;
NSNumber *boolNumber = @YES;
NSNumber *simpleFloat = @3.14f;
NSNumber *betterDouble = @3.1415;
NSNumber *someChar = @'T';
Once we have NSNumber, we can convert to any format we need.
[magicNumber intValue];
[unsignedNumber unsignedIntValue];
[longNumber longValue];
[boolNumber boolValue];
[simpleFloat floatValue];
[betterDouble doubleValue];
[someChar charValue];
NSNumber can also work with NSInteger and NSUInteger types.
Represent Other Values Using Instances of the NSValue Class
The NSNumber class is itself a subclass of the basic NSValue class.
NSString *mainString = @"this is a long string";
NSRange substringRange = [mainString rangeOfString:@"long"];
NSValue *rangeValue = [NSValue valueWithRange:substringRange];
6.3 Most Collections Are Objects
NSArray, NSSet and NSDictionary
Any item I wish to add to a collection must be an instance of an Objective-C class. The collection classes use strong references to keep track of their contents, this means that any object that we add to a collection will be kept alive at least as long as the collection is kept alive.
The basic NSArray, NSSet and NSDictionary classes are immutable, which means their contents are set at creation.
Arrays Are Ordered Collections
There is no requirement for each object to be an instance of the same class in Arrays. And this Array is ordered.
Creating Arrays
NSArray *someArray = [NSArray arrayWithObjects: someObject, someString, someNumber, someValue, nil];
In this case, the someObject, someString, someNumber, someValue can not be nil.
Liberal Syntax
NSArray *someArray = @[firstObject, secondObject, thirdObject];
We do not need to use nil to terminate the list of objects and nil is an invalid value.
Querying Array Objects
number of objects
NSUInteger numberOfItems = [someArray count];
check contain
if([someArray containsObject:someString]) { …snip… }
get the first object
if([someArray count] > 0){
NSLog(@"First item is: %@", [someArray objectAtIndex:0]);
}
Subscripting
if([someArray count] > 0){
NSLog(@"First item is: %@", someArray[0]);
}
Sorting Array Objects
…
Mutability
If we add a mutable string to an immutable array
NSMutableString *mutableString = [NSMutableString stringWithString:@"hello"];
NSArray *immutableArray = @[mutableString];
if([immutableArray count] > 0){
id string = immutableArray[0]
if([string isKindOfClass: [NSMutableString class]]){
(string appendString: @" world");
}
}
If we plan to add or remove objects from an array, we need NSMutableArray
NSMutableArray *mutableArray = [NSMutable array];
[mutableArray addObject:@"gama"];
[mutableArray addObject:@"carl"];
[mutableArray replaceObjectAtIndex:0 withObject:@"austin"];
Sets Are unordered Collections
An NSSet is unordered group of distinct objects.
NSSet *simpleSet = [NSSet setWithObjects: @"hello, world", @42, aVaue, anObject, nil];
NSNumber *number = @42
NSSet *number = [NSSet setWithObjects: number, number, number, nil];
Dictionaries Collect Key-Value Paris
NSDirectory stores objects against given keys, which can then be used for retrieval.
Creating Dictionaries
NSDictionary *dictionary = [NSDictionary dictionaryWithObjectsAndKeys:
someObject, @"anObject",
@"hello, wold", @"hellotstring",
@42, @"magicNumber",
nil];
Each object is specified before its key, and the list of objects and keys must be nil-terminated.
Literal Syntax
NSDictionary *dictionary = @{
@"anObject" : someObject,
@"hellostring" : @"hello, world",
@"magicNumber": @42
@"aValue": someValue
};
Querying Dictionaries
NSNumber *storedNumber = [dictionary[@"magicNumber"];
NSNumber *storeNumber = [dictionary objectForKey:@"magicNumber"];
Mutability
Need to use NSMutableDictionary to add and remove objects.
[dictionary setObject:@"another string" forKey:@"secondstring"];
[dictionary removeObjectForKey:@"anObject" ];
Represent nil with NSNull
We can not add nil to collection classes. So we can use NSNull.
NSNull is a singleton, so NSNull null will always return the same instance.
NSArray *array = @[ @"string", @42, [NSNull null] ];
for(id object in array ){
if(object == [NSNull null ]){
NSLog(@"Found it");
}
}
6.4 Use Collections to Persist Your Object Graph
The NSArray and NSDictionary classes make it easy to write their contents directly to disk.
NSURL *fileURL = …
NSArray *array = @[@"first", @"second", @"third"];
BOOL success = [array writeToURL:fileURL atomically:YES];
If all the objects are one of the property list types(NSArray, NSDictionary, NSString, NSData, NSDate and NSNumber), we can recreate the entire hierarchy from disk.
NSURL *fileURL = …
NSArray *array = [NSArray arrayWithContentsOfURL:fileURL];
6.5 Use the Most Efficient Collection Enumeration Techniques
Fast Enumeration Makes it Easy to Enumerate a Collection
NSArray, NSSet and NSDictionary conform to the NSFastEnumeration protocol.
for(<Type> <variable> in <collection>) {
...
}
eg.
for(id eachObject in array){
NSLog(@"Object: %@", eachObject);
}
for (NSString *eachKey in dictionary) {
id object = dictionary[eachKey];
NSLog(@"Object: %@ for key: %@", objet, eachKey);
}
Most Collections Also Support Enumerator Objects
….
References:
https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/ProgrammingWithObjectiveC/WorkingwithProtocols/WorkingwithProtocols.html#//apple_ref/doc/uid/TP40011210-CH11-SW1
https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/ProgrammingWithObjectiveC/FoundationTypesandCollections/FoundationTypesandCollections.html#//apple_ref/doc/uid/TP40011210-CH7-SW1
- 浏览: 2539712 次
- 性别:
- 来自: 成都
文章分类
最新评论
-
nation:
你好,在部署Mesos+Spark的运行环境时,出现一个现象, ...
Spark(4)Deal with Mesos -
sillycat:
AMAZON Relatedhttps://www.godad ...
AMAZON API Gateway(2)Client Side SSL with NGINX -
sillycat:
sudo usermod -aG docker ec2-use ...
Docker and VirtualBox(1)Set up Shared Disk for Virtual Box -
sillycat:
Every Half an Hour30 * * * * /u ...
Build Home NAS(3)Data Redundancy -
sillycat:
3 List the Cron Job I Have>c ...
Build Home NAS(3)Data Redundancy
发表评论
-
ionic UI(5)UI and Backend
2016-12-02 03:22 589ionic UI(5)UI and Backend 1 Pr ... -
Stanford Cource(2)Demo App Caculator
2014-06-24 01:29 896Stanford Cource(2)Demo App Ca ... -
Mono on MAC
2014-06-04 03:27 973Mono on MACJust fine the tool f ... -
IOS7 App Development Essentials(4)IPhone5, IPhone5s, IPhone5c
2014-04-11 03:59 980IOS7 App Development Essentia ... -
IOS7 App Development Essentials(3)NSUserDefaults
2014-04-11 02:58 1005IOS7 App Development Essentia ... -
IPhone and Location(2)Documents Region Monitoring and Region Sample
2013-10-18 05:10 1725IPhone and Location(2)Documents ... -
IPhone and Location(1)Documents User Location
2013-10-18 03:50 1303IPhone and Location(1)Documents ... -
Learn Objective C(6)Programming with Objective-C - Working with Blocks and Deali
2013-10-18 00:02 923Learn Objective C(6)Programming ... -
Learn Objective C(4)Programming with Objective-C - Encapsulating Data and Custom
2013-10-17 23:23 933Learn Objective C(4)Programming ... -
Learn Objective C(3)Programming with Objective-C - Defining Classes, Working wit
2013-10-17 23:09 1013Learn Objective C(3)Programmi ... -
Learn Objective C(2)Learn Objective-C in Day 6 - 4 ~ 6
2013-10-17 00:30 959Learn Objective C(2)Learn Obj ... -
Learn Object C(1) Learn Objective-C in Day 6 - 1 ~ 3
2013-10-17 00:22 1109Learn Object C(1) Learn Objec ... -
APNS(4)Recall the Process and Learn Java APNS
2013-04-18 02:48 3466APNS(4)Recall the Process and L ... -
Build the iOS Things with J2Objc
2013-04-12 03:25 2461Build the iOS Things with J2Obj ... -
APNS(3)Write the Easy Client App
2013-01-15 07:23 1691APNS(3)Write the Easy Client Ap ... -
APNS(2)Try to Finish the first Example
2013-01-14 07:56 1536APNS(2)Try to Finish the first ... -
Stanford Cource(1)MVC and Object-C
2012-12-14 14:04 1315Stanford Cource(1)MVC and Objec ... -
Some VI Tips
2012-11-15 04:48 1091Some VI Tips Today, I need to c ... -
MAC Mini Setup
2012-09-25 18:45 1325MAC Mini Setup I am dealing wit ... -
Android Talker(1)MAC Environment
2012-09-01 00:16 1920Android Talker(1)MAC Environmen ...
相关推荐
根据给出的内容,我们可以总结出以下关于Objective-C编程语言的知识点,这些知识点将覆盖从Objective-C的基础知识到高级特性,以及如何在iOS移动开发中使用Objective-C: 1. Objective-C简介 Objective-C是一种面向...
Hands-On Network Programming with C: Learn socket programming in C and write secure and optimized network code Author: Lewis Van Winkle Pub Date: 2019 ISBN: 978-1789349863 Pages: 478 Language: English...
学习Objective-C之前,建议具备一定的C语言基础,了解基本的数据类型、控制流结构和指针操作。 ### See Also 参考文档和教程对于学习Objective-C非常有帮助。官方文档提供了详细的API参考和最佳实践指南。 ### ...
"Learn Objective-C on the Mac" 这本书的配套实例代码,为学习者提供了实践的机会,加深对Objective-C的理解。 首先,让我们深入了解一下Objective-C的关键概念: 1. **消息传递**: Objective-C 是基于 Smalltalk...
《Objective-C 编程语言》是一本深入探讨Objective-C编程的资源,该压缩包包含的主文件是"The Objective-C Programming Language.pdf"。Objective-C是一种基于C语言的面向对象编程语言,广泛应用于苹果的iOS和macOS...
Programming in Objective-C, 第四版,ePub格式方便在iPad看。 第四版主要更新了 iOS5 与 ARC 的内容,与最新的 Xcode 4.5 匹配。 目录: Table of Contents 1 Introduction Part I: The Objective-C Language 2...
《Programming With Objective-C》是一本由Apple官方提供的介绍Objective-C编程语言的文档。Objective-C是一种在苹果平台上广泛使用的编程语言,尤其是在开发macOS和iOS应用程序时。在这份文档中,介绍了Objective-C...
Hands-On Network Programming with C# and .NET Core: A comprehensive guide to understanding network architecture, communication protocols, and network analysis to build secure applications compatible ...
《Object-Oriented Programming with Object C》是一本深入探讨面向对象编程(OOP)与Objective-C语言的专业书籍。Objective-C是Apple开发的一种强大的、面向对象的编程语言,主要用于iOS和macOS的应用程序开发。这...
这个"Learn Objective-C 中文版 v2"的学习资源可能是针对那些希望深入理解Objective-C语言特性和编程实践的开发者设计的。下面我们将详细探讨Objective-C的关键知识点。 1. **面向对象编程基础**: - **类与对象**...
To get started with Objective-C programming, the book provides guidance on installing and using Apple's development environment, Xcode. Xcode is a comprehensive toolset that includes everything needed...
Objective-C 2.0是Apple开发的面向对象的编程语言,它是Cocoa和Cocoa Touch框架的基础。在Objective-C 2.0中,Cocoa Foundation是核心库之一,提供了大量用于构建应用程序的基本服务。本节将深入探讨Objective-C 2.0...
标题 "l7-protocols-2009-05-10.tar" 暗示了这是一个关于网络协议的资源,特别的是,它涉及到第七层(应用层)的协议。在 OSI 模型中,第七层是最高层,处理应用程序和用户之间的交互。这个压缩包可能包含了一系列与...
综上所述,《Programming in Objective-C》第三版系统地介绍了Objective-C编程相关知识,包括Objective-C语言的基础概念、核心特性、高级应用以及与其他苹果技术的整合。这本书为开发者提供了详尽的学习资料,能够...
Chapter 5, Email Protocols, FTP, and CGI Programming, brings you the joy of automating your FTP and e-mail tasks such as manipulating your Gmail account, and reading or sending emails from a script or...
3. **协议(Protocols)**:Objective-C支持协议,这是一种类似于接口的概念,允许类遵循一组特定的方法约定,即使它们不属于同一个继承层次结构。 4. **分类(Categories)**:Objective-C允许开发者为已有的类...
Objective-C是一种广泛用于苹果平台应用程序开发的编程语言,它是C语言的一个超集,并加入了Smalltalk风格的消息传递机制。本篇教程主要面向初学者,介绍了Objective-C的基础知识点和一些核心概念。 1. Objective-C...
Routing-Protocols-and-Concepts-CCNA-2