How to calculate the age based on NSDate

Many of these answers don’t properly account for leap years and such, best is to use Apple’s methods instead of dividing by constants. Swift let birthday: NSDate = … let now = Date() let ageComponents = calendar.dateComponents([.year], from: birthday, to: now) let age = ageComponents.year Objective-C NSDate* birthday = …; NSDate* now = [NSDate date]; … Read more

Round NSDate to the nearest 5 minutes

Here’s my solution: NSTimeInterval seconds = round([date timeIntervalSinceReferenceDate]/300.0)*300.0; NSDate *rounded = [NSDate dateWithTimeIntervalSinceReferenceDate:seconds]; I did some testing and it is about ten times as fast as Voss’s solution. With 1M iterations it took about 3.39 seconds. This one performed in 0.38 seconds. J3RM’s solution took 0.50 seconds. Memory usage should be the lowest also. Not … Read more

Replace substring of NSAttributedString with another NSAttributedString

Convert your attributed string into an instance of NSMutableAttributedString. The mutable attributed string has a mutableString property. According to the documentation: “The receiver tracks changes to this string and keeps its attribute mappings up to date.” So you can use the resulting mutable string to execute the replacement with replaceOccurrencesOfString:withString:options:range:.

Print the size (megabytes) of Data in Swift

Use yourData.count and divide by 1024 * 1024. Using Alexanders excellent suggestion: func stackOverflowAnswer() { if let data = #imageLiteral(resourceName: “VanGogh.jpg”).pngData() { print(“There were \(data.count) bytes”) let bcf = ByteCountFormatter() bcf.allowedUnits = [.useMB] // optional: restricts the units to MB only bcf.countStyle = .file let string = bcf.string(fromByteCount: Int64(data.count)) print(“formatted result: \(string)”) } } With … Read more

Comparing NSDates without time component

Use this Calendar function to compare dates in iOS 8.0+ func compare(_ date1: Date, to date2: Date, toGranularity component: Calendar.Component) -> ComparisonResult passing .day as the unit Use this function as follows: let now = Date() // “Sep 23, 2015, 10:26 AM” let olderDate = Date(timeIntervalSinceNow: -10000) // “Sep 23, 2015, 7:40 AM” var order … Read more

Catching NSException in Swift

Here is some code, that converts NSExceptions to Swift 2 errors. Now you can use do { try ObjC.catchException { /* calls that might throw an NSException */ } } catch { print(“An error ocurred: \(error)”) } ObjC.h: #import <Foundation/Foundation.h> @interface ObjC : NSObject + (BOOL)catchException:(void(^)(void))tryBlock error:(__autoreleasing NSError **)error; @end ObjC.m #import “ObjC.h” @implementation ObjC … Read more