カテゴリとプロトコル

カテゴリ

あるクラスの一部分のメソッドを実現する。関係の深いもの・用途が似ているメソッドをまとめたり、Frameworkが提供しているクラスにメソッドを追加したりすることができる。

NSString+Decoration.h

#import <Foundation/Foundation.h>

@interface NSString (Decoration)
+(NSString *) stringWithDecoration: (NSString *)aString;
@end

NSString+Decoration.m

#import "NSString+Decoration.h"

@implementation NSString (Decoration)
+(NSString *)stringWithDecoration:(NSString *)aString {
    NSString *newString = [NSString stringWithFormat:@"*** %@ ***",  aString];
    return newString;
}
@end
NSLog(@"%@", [NSString stringWithDecoration:@"test"]);

プロトコル

オブジェクトの振る舞いを表すメソッドの集合で、Javaで言うところのインタフェース。

There are two varieties of protocol, formal and informal:

  • A formal protocol declares a list of methods that client classes are expected to implement. Formal protocols have their own declaration, adoption, and type-checking syntax. You can designate methods whose implementation is required or optional with the @required and @optional keywords. Subclasses inherit formal protocols adopted by their ancestors. A formal protocol can also adopt other protocols. Formal protocols are an extension to the Objective-C language.

  • An informal protocol is a category on NSObject, which implicitly makes almost all objects adopters of the protocol. (A category is a language feature that enables you to add methods to a class without subclassing it.) Implementation of the methods in an informal protocol is optional. Before invoking a method, the calling object checks to see whether the target object implements it. Until optional protocol methods were introduced in Objective-C 2.0, informal protocols were essential to the way Foundation and AppKit classes implemented delegation.

https://developer.apple.com/library/ios/#documentation/General/Conceptual/DevPedia-CocoaCore/Protocol.html

UIWebviewDelegate

@protocol UIWebViewDelegate <NSObject>

@optional
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType;
- (void)webViewDidStartLoad:(UIWebView *)webView;
- (void)webViewDidFinishLoad:(UIWebView *)webView;
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error;

@end

Delegateはのdelegateクラスを意味し、***のヘッダファイルにて定義されるのが一般的(のはず..)