面试:iOS代码整理

2018-10-17  本文已影响14人  CN_HarrySun

一、懒加载

  1. Objective-C
@interface ViewController ()
@property(nonatomic, strong) NSArray *dataArray;
@end

@implementation ViewController

- (NSArray *)dataArray {
    if (!_dataArray) {
        _dataArray = @[@"data1",@"data2",@"data3"];
    }
    return _dataArray;
}
@end
  1. Swift
lazy var dataArray: [String] = {
        let array = ["data1","data2","data3"]
        return array
    }()

二、单例

  1. Objective-C
@implementation Manager
+ (instancetype)sharedManager {
    static Manager * sharedManager;
    static dispatch_once_t predicate;
    dispatch_once(&predicate, ^{
        sharedManager = [[Manager alloc] init];
    });
    return sharedManager;
}
@end
  1. Swift
class Manager: NSObject {
    static let manager = Manager()
}

三、getter和setter

  1. Objective-C
@interface ViewController ()
@property (nonatomic, copy) NSString *name;
@end

@implementation ViewController
@synthesize name = _name;

/// 同时重写setter和getter时需要synthesize
- (void)setName:(NSString *)name {
    
    if (_name != name) {
        [_name release];
        _name = [name copy];
    }
    _name = name;
}

- (NSString *)name {
    return _name;
}
  1. Swift
// swift一般不重写getter和setter方法,一般都是些willSet或者didSet
    var name: String? {
        willSet {
            self.name = newValue
        }
        didSet {
            print(self.name)
        }
    }

四、冒泡排序

  1. Objective-C
NSMutableArray * array = [@[@100, @120, @50, @10, @40, @60, @1] mutableCopy];
NSLog(@"%@",[self bubblingSortWithArray:array]);

- (NSArray *)bubblingSortWithArray:(NSMutableArray *)array {
    for (int i = 0; i < array.count; i ++) {
        for (int j = 0; j < array.count - 1 - i; j ++) {
            if (array[j] > array[j + 1]) {
                [array exchangeObjectAtIndex:j withObjectAtIndex:j + 1];
            }
        }
    }
    return array;
}
  1. Swift
var array = [100, 120, 50, 10, 40, 60, 1]
print(bubblingSort(array: &array))

func bubblingSort(array: inout [Int]) -> [Int] {
        for i in 0..<array.count {
            for j in 0..<array.count - i - 1 {
                if array[j] > array[j + 1] {
                    array.swapAt(j, j + 1)
                }
            }
        }
        return array
    }
上一篇 下一篇

猜你喜欢

热点阅读