本文目錄一覽:
什麼時候用懶載入
1.懶載入基本
懶載入——也稱為延遲載入,即在需要的時候才載入(效率低,佔用內存小)。所謂懶載入,寫的是其get方法.
注意:如果是懶載入的話則一定要注意先判斷是否已經有了,如果沒有那麼再去進行實例化
2.使用懶載入的好處:
(1)不必將創建對象的代碼全部寫在viewDidLoad方法中,代碼的可讀性更強
(2)每個控制項的getter方法中分別負責各自的實例化處理,代碼彼此之間的獨立性強,松耦合
3.代碼示例
1 //
2 // YYViewController.m
3 // 03-圖片瀏覽器初步
4 //
5 // Created by apple on 14-5-21.
6 // Copyright (c) 2014年 itcase. All rights reserved.
7 //
8
9 #import “YYViewController.h”
10
11 #define POTOIMGW 200
12 #define POTOIMGH 300
13 #define POTOIMGX 60
14 #define POTOIMGY 50
15
16 @interface YYViewController ()
17
18 @property(nonatomic,strong)UILabel *firstlab;
19 @property(nonatomic,strong)UILabel *lastlab;
20 @property(nonatomic,strong)UIImageView *icon;
21 @property(nonatomic,strong)UIButton *leftbtn;
22 @property(nonatomic,strong)UIButton *rightbtn;
23 @property(nonatomic,strong)NSArray *array;
24 @property(nonatomic ,assign)int i;
25 -(void)change;
26 @end
27
28
29
30 @implementation YYViewController
31
32 – (void)viewDidLoad
33 {
34 [super viewDidLoad];
35 [self change];
36 }
37
38 -(void)change
39 {
40 [self.firstlab setText:[NSString stringWithFormat:@”%d/5″,self.i+1]];
41 //先get再set
42
43 self.icon.image=[UIImage imageNamed:self.array[self.i][@”name”]];
44 self.lastlab.text=self.array[self.i][@”desc”];
45
46 self.leftbtn.enabled=(self.i!=0);
47 self.rightbtn.enabled=(self.i!=4);
48 }
49
50 //延遲載入
51 /**1.圖片的序號標籤*/
52 -(UILabel *)firstlab
53 {
54 //判斷是否已經有了,若沒有,則進行實例化
55 if (!_firstlab) {
56 _firstlab=[[UILabel alloc]initWithFrame:CGRectMake(20, 10, 300, 30)];
57 [_firstlab setTextAlignment:NSTextAlignmentCenter];
58 [self.view addSubview:_firstlab];
59 }
60 return _firstlab;
61 }
62
63 /**2.圖片控制項的延遲載入*/
64 -(UIImageView *)icon
65 {
66 //判斷是否已經有了,若沒有,則進行實例化
67 if (!_icon) {
68 _icon=[[UIImageView alloc]initWithFrame:CGRectMake(POTOIMGX, POTOIMGY, POTOIMGW, POTOIMGH)];
69 UIImage *image=[UIImage imageNamed:@”biaoqingdi”];
70 _icon.image=image;
71 [self.view addSubview:_icon];
72 }
73 return _icon;
74 }
75
76 /**3.描述控制項的延遲載入*/
77 -(UILabel *)lastlab
78 {
79 //判斷是否已經有了,若沒有,則進行實例化
80 if (!_lastlab) {
81 _lastlab=[[UILabel alloc]initWithFrame:CGRectMake(20, 400, 300, 30)];
82 [_lastlab setTextAlignment:NSTextAlignmentCenter];
83 [self.view addSubview:_lastlab];
84 }
85 return _lastlab;
86 }
87
88 /**4.左鍵按鈕的延遲載入*/
89 -(UIButton *)leftbtn
90 {
91 //判斷是否已經有了,若沒有,則進行實例化
92 if (!_leftbtn) {
93 _leftbtn=[UIButton buttonWithType:UIButtonTypeCustom];
94 _leftbtn.frame=CGRectMake(0, self.view.center.y, 40, 40);
95 [_leftbtn setBackgroundImage:[UIImage imageNamed:@”left_normal”] forState:UIControlStateNormal];
96 [_leftbtn setBackgroundImage:[UIImage imageNamed:@”left_highlighted”] forState:UIControlStateHighlighted];
97 [self.view addSubview:_leftbtn];
98 [_leftbtn addTarget:self action:@selector(leftclick:) forControlEvents:UIControlEventTouchUpInside];
99 }
100 return _leftbtn;
101
102 }
103
104 /**5.右鍵按鈕的延遲載入*/
105 -(UIButton *)rightbtn
106 {
107 if (!_rightbtn) {
108 _rightbtn=[UIButton buttonWithType:UIButtonTypeCustom];
109 _rightbtn.frame=CGRectMake(POTOIMGX+POTOIMGW+10, self.view.center.y, 40, 40);
110 [_rightbtn setBackgroundImage:[UIImage imageNamed:@”right_normal”] forState:UIControlStateNormal];
111 [_rightbtn setBackgroundImage:[UIImage imageNamed:@”right_highlighted”] forState:UIControlStateHighlighted];
112 [self.view addSubview:_rightbtn];
113 [_rightbtn addTarget:self action:@selector(rightclick:) forControlEvents:UIControlEventTouchUpInside];
114 }
115 return _rightbtn;
116 }
117
118 //array的get方法
119 -(NSArray *)array
120 {
121 if (_array==nil) {
122 NSString *path=[[NSBundle mainBundle] pathForResource:@”data” ofType:@”plist”];
123 _array=[[NSArray alloc]initWithContentsOfFile:path];
124 }
125 return _array;
126 }
127
128 -(void)rightclick:(UIButton *)btn
129 {
130 self.i++;
131 [self change];
132 }
133
134 -(void)leftclick:(UIButton *)btn
135 {
136 self.i–;
137 [self change];
138 }
139
140 @end
python作業求幫助
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# File name: parabolic
# Project name: parabolic_equation
“””
.. moduleauthor::
.. Module.. name parabolic of procjet parabolic_equation
“””
from sympy import *
import matplotlib.pyplot as plt
import numpy as np
def _filterComplex(inputvalue, description=’inputvalue’):
try:
str(inputvalue).index(‘I’)
except ValueError:
return False
else:
return True
def _checkBool(inputvalue, description=’inputvalue’):
“””
:param inputvalue:
:param description:
:return:
“””
if not isinstance(inputvalue, bool):
raise TypeError(
‘The {0} must be boolean. Given: {1!r}’.format(description, inputvalue))
def _checkNumerical(inputvalue, description=’inputvalue’):
“””
:param inputvalue:
:param description:
:return:
“””
try:
inputvalue + 1
except TypeError:
raise TypeError(
‘The {0} must be numerical. Given: {1!r}’.format(description, inputvalue))
def _drawTowPara(expr_1, expr_2, inputmin, inputmax ,step=0.1):
“””
:param expr_1:
:param expr_2:
:param inputmin:
:param inputmax:
:param step:
:param expr_1_evalwithY:
:param expr_2_evalwithY:
:return:
“””
_checkNumerical(inputmin, ‘xmin’)
_checkNumerical(inputmax, ‘xmax’)
_checkNumerical(step, ‘step’)
y1List = []
x1List = []
y2List = []
x2List = []
if expr_1.vertical is True:
x1List = np.arange(inputmin, inputmax, step)
for x in x1List:
y1List.append(expr_1.evaluates_Y(x))
else:
y1List = np.arange(inputmin, inputmax, step)
for y in y1List:
x1List.append(expr_1.evaluates_X(y))
if expr_2.vertical is True:
x2List = np.arange(inputmin, inputmax, step)
for x in x2List:
y2List.append(expr_2.evaluates_Y(x))
else:
y2List = np.arange(inputmin, inputmax, step)
for y in y2List:
x2List.append(expr_2.evaluates_X(y))
plt.plot(x1List, y1List, ‘+’)
plt.plot(x2List, y2List, ‘-‘)
plt.show()
def _solveCrossing(expr_1, expr_2):
“””
:param expr_1:
:param expr_2:
:return:
“””
x = Symbol(‘x’)
y = Symbol(‘y’)
print “Given the first expression: {0!r}”.format(expr_1.expr)
print “Given the first expression: {0!r}”.format(expr_2.expr)
ResultList = solve([expr_1.expr, expr_2.expr], [x, y])
Complex = False
ResultListTrue = []
for i in range(0, (len(ResultList)),1):
if _filterComplex(ResultList[i][0], ‘x’) or _filterComplex(ResultList[i][1], ‘y’):
Complex = True
else:
ResultListTrue.append(ResultList[i])
if len(ResultListTrue) == 0 and Complex:
print “Two hyperbolic do not intersect, and there is imaginary value.”
elif len(ResultListTrue) == 1:
print “Two hyperbolic tangent.:”
print ResultListTrue
else:
print “Two hyperbolic intersection, and Points are:”
for iterm in ResultListTrue:
print iterm
class Parabolic():
“””
“””
def __init__(self, a, b, c, vertical=True):
“””
:return:
“””
_checkNumerical(a, ‘a’)
_checkNumerical(b, ‘b’)
_checkNumerical(c, ‘c’)
_checkBool(vertical, ‘vertical’)
self.a = a
self.b = b
self.c = c
self.vertical = vertical
self.y = Symbol(‘y’)
self.x = Symbol(‘x’)
self.xarray = []
self.yarray = []
if vertical is True:
self.expr = (self.x**2)*self.a + self.x*self.b + self.c
else:
self.expr = (self.y**2)*self.a + self.y*self.b + self.c
def __repr__(self):
“””
:return:
“””
if self.vertical is True:
return “The Equation look like: {0!r}”.format(self.expr)
else:
return “The Equation look like: {0!r}”.format(self.expr)
def evaluates_X(self, inputvalue):
“””
:param inputvalue:
:return:
“””
_checkNumerical(inputvalue, ‘y’)
return self.expr.subs(self.y, inputvalue)
def evaluates_Y(self, inputvalue):
“””
:param inputvalue:
:return:
“””
_checkNumerical(inputvalue, ‘x’)
return self.expr.subs(self.x, inputvalue)
def getArrays(self, inputmin, inputmax, step=1):
“””
:param inputmin:
:param inputmax:
:param step:
:return:
“””
_checkNumerical(inputmin, ‘xmin’)
_checkNumerical(inputmax, ‘xmax’)
_checkNumerical(step, ‘step’)
if self.vertical is True:
for x in range(inputmin, inputmax, step):
self.xarray.append(x)
self.yarray.append(self.evaluates_Y(x))
else:
for y in range(inputmin, inputmax, step):
self.yarray.append(y)
self.xarray.append(self.evaluates_X(y))
def drawPara(self, inputmin, inputmax, step=1):
“””
:param inputmin:
:param inputmax:
:param step:
:return:
“””
_checkNumerical(inputmin, ‘xmin’)
_checkNumerical(inputmax, ‘xmax’)
_checkNumerical(step, ‘step’)
yList = []
xList = []
if self.vertical is True:
xList = np.arange(inputmin, inputmax, step)
for x in xList:
yList.append(self.evaluates_Y(x))
else:
yList = np.arange(inputmin, inputmax, step)
for y in yList:
xList.append(self.evaluates_X(y))
plt.plot(xList, yList, ‘+’)
plt.show()
if __name__ == ‘__main__’:
pa1 = Parabolic(-5,3,6)
pa2 = Parabolic(-5,2,5, False)
print pa1
print pa2
_solveCrossing(pa1, pa2)
_drawTowPara(pa1, pa2, -10, 10, 0.1)
# 這就是你想要的,代碼解決了你的大部分問題,可以求兩條雙曲線交點,或者直線與雙曲線交#點,或者兩直線交點. 不過定義雙曲線時候使用的是一般式.也也儘可能做了測試,如果有#問題的話,追問吧
iOS 高德地圖軌跡回放的 思路, 及方法
// 開始,公司要求製作一段跑步軌跡 在地圖上的 動畫回放, 傳入一段經緯度,
開始一想,這不是很簡單嗎, 高德地圖有可以把經緯度轉換成坐標點的方法
/**
* @brief 將經緯度轉換為指定view坐標系的坐標
* @param coordinate 經緯度
* @param view 指定的view
* @return 基於指定view坐標系的坐標
*/
– (CGPoint)convertCoordinate:(CLLocationCoordinate2D)coordinate toPointToView:(UIView *)view;
// 我把經緯度轉換成坐標點, 然後構建 path
/* 構建path, 調用著負責釋放內存. */
– (CGMutablePathRef)pathForPoints:(CGPoint *)points count:(NSUInteger)count
{
if (points == NULL || count = 1)
{
return NULL;
}
CGMutablePathRef path = CGPathCreateMutable();
CGPathAddLines(path, NULL, points, count);
return path;
}
// 在然後直接用 path ,初始化一個 CAShapeLayer ,做成動畫不就成了 嗎, 在它跑完之後直接刪除, 再用 高德地圖的折線替換,
// 這種方法也可以, 但是後來需求改了, 要求地圖旋轉,並且地圖中心點一直在跑動的點上,
這樣,我以屏幕坐標構建的 path 一旦地圖旋轉, 就全亂了,
// 後來我又想到一個辦法, 我從地圖手機上定位畫線得到的靈感, 我把經緯度點兩個兩個連成一個個短的折線,放到一個數組裡面 ,然後定義了一個 index 屬性, 再用一個定時器不停的循環, 在定時器的方法中,用
[self.mapView addOverlay:self.mapOverlayArr[self.index] level:MAOverlayLevelAboveRoads];
不停載入線路在地圖上, 同時把地圖的中心點, 定位在 經緯度數組取到的最新的經緯度上
CLLocation * location = self.locationArray[self.index];
[self.mapView setCenterCoordinate:location.coordinate animated:NO];
,這樣就能保證地圖中心一直在跑動的點上, 而且定時器 方法 載入線路夠快的話, 就能產生動畫效果,
然而, 又出現了問題, 定時器不停的運行
mapView 不停的載入 addOverlay ,使得屏幕非常卡, 經緯度少的話還看不出來, 一旦經緯度多了, 卡的不要不要的, 完全受不了, 而且手機非常燙, 電池都快燒壞了,, 所以這種方法不可行, 至少不完善
// 後來我研究高德地圖的畫線方法, 發現一個 方法
/**
* @brief 重新設置折線坐標點. since 5.0.0
* @param coords 指定的經緯度坐標點數組, C數組,內部會做copy,調用者負責內存管理
* @param count 坐標點的個數
* @return 是否設置成功
*/
– (BOOL)setPolylineWithCoordinates:(CLLocationCoordinate2D *)coords count:(NSInteger)count;
// 這個方法只用一條折線, 但是可以不停的改變這條折線的位置,
終於利用這個方法 不卡了, 畫線的過程中 FPS 60 左右, 完美
// 因為文件太大就 不上傳了
Python數據結構之Array用法實例
Python數據結構之Array用法實例
這篇文章主要介紹了Python數據結構之Array用法實例,較為詳細的講述了Array的常見用法,具有很好的參考借鑒價值,需要的朋友可以參考下
import ctypes
class Array:
def __init__(self, size):
assert size 0, “Array size must be 0 “
self._size = size
pyArrayType = ctypes.py_object * size
self._elements = pyArrayType()
self.clear(None)
def clear(self, value):
for index in range(len(self)):
self._elements[index] = value
def __len__(self):
return self._size
def __getitem__(self, index):
assert index = 0 and index len(self), “index must =0 and = size”
return self._elements[index]
def __setitem__(self, index, value):
assert index = 0 and index len(self), “index must =0 and = size”
self._elements[index] = value
def __iter__(self):
return _ArrayIterator(self._elements)
class _ArrayIterator:
def __init__(self, theArray):
self._arrayRef = theArray
self._curNdr = 0
def __next__(self):
if self._curNdr len(theArray):
entry = self._arrayRef[self._curNdr]
sllf._curNdr += 1
return entry
else:
raise StopIteration
def __iter__(self):
return self
class Array2D :
def __init__(self, numRows, numCols):
self._theRows = Array(numCols)
for i in range(numCols):
self._theRows[i] = Array(numCols)
def numRows(self):
return len(self._theRows)
def numCols(self):
return len(self._theRows[0])
def clear(self, value):
for row in range(self.numRows):
self._theRows[row].clear(value)
def __getitem__(self, ndxTuple):
assert len(ndxTuple) == 2, “the tuple must 2”
row = ndxTuple[0]
col = ndxTuple[1]
assert row=0 and row len(self.numRows())
and col=0 and collen(self.numCols),
“array subscrpt out of range”
theArray = self._theRows[row]
return theArray[col]
def __setitem__(self, ndxTuple, value):
assert len(ndxTuple)==2, “the tuple must 2”
row = ndxTuple[0]
col = ndxTuple[1]
assert row = 0 and row len(self.numRows)
and col = 0 and col len(self.numCols),
“row and col is invalidate”
theArray = self._theRows[row];
theArray[col] = value
希望本文所述對大家的Python程序設計有所幫助。
iOS 判斷數組為空
伺服器返回有這個數組 但是這個數組裡面是空的話
if(self.array.count == 0){}判斷裡面成員個數,個數是0 就是空了
Python多線程
那是當然。你這樣寫就可以了
self.p[:]=array
這樣寫法的含義就是指針不變。只換內容。這樣就可以同步了。
你的寫法是,新建一個數組,再把指針緞帶self.p,如果其它的線程就會出問題。
另外你的p應該放在__init__之前。引用時使用T.p來引用,這樣更合理一些。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/244391.html