-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathBlogObject.m
executable file
·120 lines (86 loc) · 3.02 KB
/
BlogObject.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
//
// BlogObject.m
// ABFRealmSearchViewControllerExample
//
// Created by Adam Fish on 8/11/15.
// Copyright (c) 2015 Adam Fish. All rights reserved.
//
#import "BlogObject.h"
@implementation BlogObject
#pragma mark - RLMObject
+ (NSString *)primaryKey
{
return @"blogId";
}
// Specify default values for properties
+ (NSDictionary *)defaultPropertyValues
{
return @{@"title" : @"",
@"urlString" : @"",
@"date" : [NSDate distantPast],
@"content" : @"",
@"imageURLString" : @"",
};
}
// Specify properties to ignore (Realm won't persist these)
+ (NSArray *)ignoredProperties
{
return @[@"url",
@"imageURL"];
}
#pragma mark - Getters
- (NSURL *)url
{
return [NSURL URLWithString:self.urlString];
}
- (NSURL *)imageURL
{
return [NSURL URLWithString:self.imageURLString];
}
#pragma mark - Public Class
+ (void)loadBlogData
{
NSString *jsonFilePath = [[NSBundle mainBundle] pathForResource:@"blog" ofType:@"json"];
NSData *jsonData = [NSData dataWithContentsOfFile:jsonFilePath];
NSError *error;
NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData:jsonData
options:NSJSONReadingMutableContainers
error:&error];
if (error) {
NSLog(@"JSON Serialization Error: %@",error.localizedDescription);
}
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateStyle = NSDateFormatterLongStyle;
NSUInteger index = 0;
for (NSDictionary *blogData in jsonArray) {
BlogObject *blog = [[BlogObject alloc] init];
blog.title = blogData[@"title"];
// Create the correct Realm URL
NSString *url = [NSString stringWithFormat:@"http://www.realm.io%@",blogData[@"url"]];
blog.urlString = url;
blog.date = [dateFormatter dateFromString:blogData[@"date"]];
blog.content = blogData[@"content"];
blog.imageURLString = blogData[@"image"];
blog.emoji = [self randomEmoji];
blog.blogId = index;
[[RLMRealm defaultRealm] transactionWithBlock:^{
[[RLMRealm defaultRealm] addOrUpdateObject:blog];
}];
index ++;
}
}
static NSArray *emojiArray;
+ (NSString *)randomEmoji
{
if (!emojiArray) {
NSString *emojiFilePath = [[NSBundle mainBundle] pathForResource:@"emoji" ofType:@"json"];
NSData *emojiData = [NSData dataWithContentsOfFile:emojiFilePath];
NSError *error;
emojiArray = [NSJSONSerialization JSONObjectWithData:emojiData
options:NSJSONReadingMutableContainers
error:&error];
}
NSInteger randomIndex = arc4random_uniform((u_int32_t)emojiArray.count);
return emojiArray[randomIndex];
}
@end