Skip to content

Instantly share code, notes, and snippets.

@ijoshsmith
ijoshsmith / Array+Shuffle.swift
Last active December 24, 2018 21:55
Randomly shuffle a Swift array
import Foundation
extension Array
{
/** Randomizes the order of an array's elements. */
mutating func shuffle()
{
for _ in 0..<10
{
sort { (_,_) in arc4random() < arc4random() }
@ijoshsmith
ijoshsmith / SelfFromBlockInARC
Created September 28, 2012 17:59
Safely access self from block using ARC
__weak id weakSelf = self;
void (^aBlock)(void) = ^{
<MyClass> *strongSelf = weakSelf;
if (strongSelf)
{
// strongSelf->someIvar = 42;
// [strongSelf someMethod];
}
};
@ijoshsmith
ijoshsmith / PreferredViewSizeLookup.m
Created September 26, 2012 04:17
Inspect a View's NIB to determine its preferred/natural size
// This code assumes that ARC is enabled.
// Returns the size of this View in its NIB.
+ (CGSize)preferredSize
{
static NSValue *sizeBox = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
// Assumption: The XIB file name matches this UIView subclass name.
UINib *nib = [UINib nibWithNibName:NSStringFromClass(self) bundle:nil];